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
Why can't a Python class definition assign a closure variable to itself?
1,445,207
<p>Why doesn't the following work in Python?</p> <pre><code>def make_class(a): class A(object): a=a return A </code></pre>
2
2009-09-18T15:17:37Z
1,445,231
<p>works just fine:</p> <pre><code>&gt;&gt;&gt; def make_class(a): class A(object): _a=a return A &gt;&gt;&gt; make_class('df') &lt;class '__main__.A'&gt; &gt;&gt;&gt; make_class('df')._a 'df' </code></pre> <p>btw, <code>function</code> is not a reserved keyword in Python.</p>
9
2009-09-18T15:21:23Z
[ "python", "closures" ]
Why can't a Python class definition assign a closure variable to itself?
1,445,207
<p>Why doesn't the following work in Python?</p> <pre><code>def make_class(a): class A(object): a=a return A </code></pre>
2
2009-09-18T15:17:37Z
1,445,514
<p>Try</p> <pre><code>def make_class(a): class A(object): pass A.a=a return A </code></pre> <p>The error you get (<code>NameError: name 'a' is not defined</code>) is because the name <code>a</code> in the class shadows the parameter <code>a</code> of the function; hence there is no <code>a</code> defined when you try "a=a" in your code. In other words, the right side <code>a</code> is <em>not</em> the <code>a</code> from the <code>def</code>; instead Python looks for it in the class <code>A</code> since <code>a</code> was already mentioned on the left side of the assignment.</p> <p>This becomes more clean with functions:</p> <pre><code>x = 1 def a(x): print 'a:',x x = 3 def b(): print 'b:',x b() a(2) def c(): x = x </code></pre> <p>Obviously, the first print should print 2, not 1, so the parameter <code>x</code> of <code>a</code> must shadow the global variable <code>x</code>. <code>b</code> is defined in a scope where <code>x</code> is known as a parameter of <code>a</code>, so the print works.</p> <p>If you try to call <code>c</code>, however, you get <code>UnboundLocalError: local variable 'x' referenced before assignment</code> since Python doesn't bind global variables automatically. To fix this, you must add <code>global x</code> before the assignment.</p> <p>Your case looks more like this:</p> <pre><code>x = 1 def a(x): print 'a:',x x = 3 def b(): x = x print 'b:',x b() a(2) </code></pre> <p>While printing <code>x</code> worked in the example above, assignment doesn't work. This is a safety measure to make sure that variables don't leak. The solution is to use a default parameter to "copy" the variable into <code>b</code>'s scope:</p> <pre><code>x = 1 def a(x): print 'a:',x x = 3 def b(x=x): x = x print 'b:',x b() a(2) </code></pre> <p>To solve your problem, you would need to tell Python "make the parameter <code>a</code> of <code>make_class</code> visible in <code>A</code>" and you would need to do that before you try to assign the field <code>a</code> of the class. This is not possible in Python. If you could make <code>a</code> visible, the assignment would change the parameter, not the field, since Python has no way to distinguish the two.</p> <p>Since you can't make it visible, there is no <code>a</code> to read from, hence the <code>NameError</code>.</p> <p>See <a href="http://docs.python.org/reference/executionmodel.html" rel="nofollow">here</a> for an explanation of the scope of a name in Python.</p>
2
2009-09-18T16:07:59Z
[ "python", "closures" ]
Why can't a Python class definition assign a closure variable to itself?
1,445,207
<p>Why doesn't the following work in Python?</p> <pre><code>def make_class(a): class A(object): a=a return A </code></pre>
2
2009-09-18T15:17:37Z
1,453,254
<p>Let's use a simpler example for the same problem:</p> <pre><code>a = 'something' def boo(): a = a boo() </code></pre> <p>This fails because assignments in python, without an accompanying <code>global</code> or <code>nonlocal</code> statement, means that the assigned name is local to the current scope. This happens not just in functions but also in class definitions.</p> <p>This means that you can't use the same name for a global and local variable and use them both. You can use the workaround from Aaron Digulia's answer, or use a different name:</p> <pre><code>def make_class(_a): class A(object): a = _a return A </code></pre>
6
2009-09-21T07:31:08Z
[ "python", "closures" ]
Writing a function to display current day using time_t?
1,445,236
<p>I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on.</p> <p>The full script is hosted <a href="http://paste.wowace.com/oc1wapgrfk2js834/" rel="nofollow" title="wowace pastebin - hi from the tooltip">here</a>.</p> <p>Writing converters for the year and month were fairly easy, but I've hit a serious brick wall trying to get the day working. As you can see, I've been trying to brute-force my way all the way from 1970 to today. Unfortunately, the day comes out as -105.</p> <p>Does anyone know of a better way to do it, or a way to fix up what I have attempted here? It's currently 3:30 AM, so it's quite possible I'm missing something obvious.</p> <p>Sorry, I forgot to note that I'm doing this manually in order to learn python. Doing it via date functions defeats the purpose, unfortunately.</p>
1
2009-09-18T15:21:53Z
1,445,259
<p>You could do it either with <a href="http://docs.python.org/library/time.html#time.strftime" rel="nofollow"><code>time.strftime</code></a>:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strftime('%Y %B %d') '2009 September 18' </code></pre> <p>or with <a href="http://docs.python.org/library/datetime.html#datetime.date.strftime" rel="nofollow"><code>datetime.date.strftime</code></a>:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.date.today().strftime('%Y %B %d') '2009 September 18' </code></pre>
3
2009-09-18T15:25:42Z
[ "python", "time", "time-t" ]
Writing a function to display current day using time_t?
1,445,236
<p>I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on.</p> <p>The full script is hosted <a href="http://paste.wowace.com/oc1wapgrfk2js834/" rel="nofollow" title="wowace pastebin - hi from the tooltip">here</a>.</p> <p>Writing converters for the year and month were fairly easy, but I've hit a serious brick wall trying to get the day working. As you can see, I've been trying to brute-force my way all the way from 1970 to today. Unfortunately, the day comes out as -105.</p> <p>Does anyone know of a better way to do it, or a way to fix up what I have attempted here? It's currently 3:30 AM, so it's quite possible I'm missing something obvious.</p> <p>Sorry, I forgot to note that I'm doing this manually in order to learn python. Doing it via date functions defeats the purpose, unfortunately.</p>
1
2009-09-18T15:21:53Z
1,445,264
<p>Why not use:</p> <pre><code>from datetime import datetime the_date = datetime.fromtimestamp(the_time) print(the_date.strftime('%Y %B %d')) </code></pre> <p>The datetime module handles all the edge cases -- leap years, leap seconds, leap days -- as well as time zone conversion (with optional second argument)</p>
8
2009-09-18T15:26:30Z
[ "python", "time", "time-t" ]
Writing a function to display current day using time_t?
1,445,236
<p>I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on.</p> <p>The full script is hosted <a href="http://paste.wowace.com/oc1wapgrfk2js834/" rel="nofollow" title="wowace pastebin - hi from the tooltip">here</a>.</p> <p>Writing converters for the year and month were fairly easy, but I've hit a serious brick wall trying to get the day working. As you can see, I've been trying to brute-force my way all the way from 1970 to today. Unfortunately, the day comes out as -105.</p> <p>Does anyone know of a better way to do it, or a way to fix up what I have attempted here? It's currently 3:30 AM, so it's quite possible I'm missing something obvious.</p> <p>Sorry, I forgot to note that I'm doing this manually in order to learn python. Doing it via date functions defeats the purpose, unfortunately.</p>
1
2009-09-18T15:21:53Z
1,445,414
<p>(I'm assuming you do this to learn Python, so I'll point out the errors in your code).</p> <pre><code>&gt;&gt;&gt; years = SecondsSinceEpoch / 31540000 </code></pre> <p>Nonononono. You can't do that. Some years have 31536000 seconds, others have 31622400 seconds.</p> <pre><code>&gt;&gt;&gt; if calendar.isleap(yeariterator) == True: </code></pre> <p>You don't need to test if a true value is true. :-) Do:</p> <pre><code>&gt;&gt;&gt; if calendar.isleap(yeariterator): </code></pre> <p>Instead.</p> <p>Also change:</p> <pre><code>&gt;&gt;&gt; yeariterator = 1969 &gt;&gt;&gt; iterator = 0 &gt;&gt;&gt; while yeariterator &lt; yearsfordayfunction: &gt;&gt;&gt; yeariterator = yeariterator + 1 </code></pre> <p>To:</p> <blockquote> <blockquote> <blockquote> <p>for yeariterator in range(1970, yearsfordayfunction):</p> </blockquote> </blockquote> </blockquote> <p>That will also fix your error: You don't stop until AFTER 2009, so you get the answer -105, because there is 105 days left of the year.</p> <p>And also, there's not much point in calculating month by month. Year by year works fine.</p> <pre><code> for yeariterator in range(1970, yearsfordayfunction): if calendar.isleap(yeariterator) == True: days = days - 366 else: days = days - 365 </code></pre> <p>And an indent of 8 spaces is a lot. 4 is more common.</p> <p>Also, I'd calculate year and day of year in one method, instead of doing it twice.</p> <pre><code>def YearDay(): SecondsSinceEpoch = int(time.time()) days = SecondsSinceEpoch // 86400 # Double slash means floored int. year = 1970 while True: if calendar.isleap(year): days -= 366 else: days -= 365 year += 1 if calendar.isleap(year): if days &lt;= 366: return year, days else: if days &lt;= 365: return year, days def MonthDay(year, day): if calendar.isleap(year): monthstarts = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] else: monthstarts = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] month = 0 for start in monthstarts: if start &gt; day: return month, day - monthstarts[month-1] + 1 month += 1 </code></pre>
1
2009-09-18T15:51:27Z
[ "python", "time", "time-t" ]
Writing a function to display current day using time_t?
1,445,236
<p>I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on.</p> <p>The full script is hosted <a href="http://paste.wowace.com/oc1wapgrfk2js834/" rel="nofollow" title="wowace pastebin - hi from the tooltip">here</a>.</p> <p>Writing converters for the year and month were fairly easy, but I've hit a serious brick wall trying to get the day working. As you can see, I've been trying to brute-force my way all the way from 1970 to today. Unfortunately, the day comes out as -105.</p> <p>Does anyone know of a better way to do it, or a way to fix up what I have attempted here? It's currently 3:30 AM, so it's quite possible I'm missing something obvious.</p> <p>Sorry, I forgot to note that I'm doing this manually in order to learn python. Doing it via date functions defeats the purpose, unfortunately.</p>
1
2009-09-18T15:21:53Z
1,447,565
<p>I'll also point out something odd in the code you posted:</p> <pre><code> try: SecondsSinceEpoch = time.time() except IOError: Print("Unable to get your system time!") </code></pre> <p>1.) Why would <code>time.time()</code> raise an IOError? As far as I know it's impossible for that function to raise an error, it should always return a value.</p> <p>2.) <code>Print</code> should be <code>print</code>.</p> <p>3.) Even if <code>time.time</code> did raise an <code>IOError</code> exception, you are swallowing the exception, which you probably don't want to do. The next line requires <code>SecondsSinceEpoch</code> to be defined, so that will just raise another (more confusing) exception.</p>
0
2009-09-19T02:40:53Z
[ "python", "time", "time-t" ]
How can I find out why subprocess.Popen wait() waits forever if stdout=PIPE?
1,445,627
<p>I have a program that writes to stdout and possibly stderr. I want to run it from python, capturing the stdout and stderr. My code looks like:</p> <pre><code>from subprocess import * p = Popen( exe, shell=TRUE, stdout=PIPE, stderr=PIPE ) rtrncode = p.wait() </code></pre> <p>For a couple of programs, this works fine, but when I added a new one, the new one hangs forever. If I remove <code>stdout=PIPE</code>, the program writes its output to the console and finishes and everything is fine. How can I determine what's causing the hang?</p> <p>Using python 2.5 on Windows XP. The program does not read from stdin nor does it have any kind of user input (i.e. "hit a key").</p>
12
2009-09-18T16:30:59Z
1,445,647
<p>When a pipe's buffer fills up (typically 4KB or so), the writing process stops until a reading process has read some of the data in question; but here you're reading nothing until the subprocess is done, hence the deadlock. <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.wait">The docs</a> on <code>wait</code> put it very clearly indeed:</p> <blockquote> <p><strong>Warning</strong> This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.</p> </blockquote> <p>If you can't use <code>communicate</code> for some reason, have the subprocess write to a temporary file, and then you can <code>wait</code> and read that file when it's ready -- writing to a file, instead of to a pipe, does not risk deadlock.</p>
28
2009-09-18T16:36:04Z
[ "python", "subprocess" ]
How can I find out why subprocess.Popen wait() waits forever if stdout=PIPE?
1,445,627
<p>I have a program that writes to stdout and possibly stderr. I want to run it from python, capturing the stdout and stderr. My code looks like:</p> <pre><code>from subprocess import * p = Popen( exe, shell=TRUE, stdout=PIPE, stderr=PIPE ) rtrncode = p.wait() </code></pre> <p>For a couple of programs, this works fine, but when I added a new one, the new one hangs forever. If I remove <code>stdout=PIPE</code>, the program writes its output to the console and finishes and everything is fine. How can I determine what's causing the hang?</p> <p>Using python 2.5 on Windows XP. The program does not read from stdin nor does it have any kind of user input (i.e. "hit a key").</p>
12
2009-09-18T16:30:59Z
1,445,653
<p>Take a look at the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.wait" rel="nofollow">docs</a>. It states that you shouldn't use wait as it can cause a dead lock. Try using <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow">communicate</a>.</p>
1
2009-09-18T16:37:11Z
[ "python", "subprocess" ]
Whats the proper idiom for naming django model fields that are python reserved names?
1,445,971
<p>I have a model that needs to have a field named <code>complex</code> and another one named <code>type</code>. Those are both python reserved names. According to PEP 8, I should name them <code>complex_</code> and <code>type_</code> respectively, but django won't allow me to have fields named with a trailing underscore. Whats the proper way to handle this?</p>
5
2009-09-18T17:48:09Z
1,446,128
<p>Do you really want to use the <code>db_column="complex"</code> argument and call your field something else?</p>
1
2009-09-18T18:18:43Z
[ "python", "django", "idioms" ]
Whats the proper idiom for naming django model fields that are python reserved names?
1,445,971
<p>I have a model that needs to have a field named <code>complex</code> and another one named <code>type</code>. Those are both python reserved names. According to PEP 8, I should name them <code>complex_</code> and <code>type_</code> respectively, but django won't allow me to have fields named with a trailing underscore. Whats the proper way to handle this?</p>
5
2009-09-18T17:48:09Z
1,446,132
<p>There's no problem with those examples. Just use <code>complex</code> and <code>type</code>. You are only shadowing in a very limited scope (the class definition itself). After that, you'll be accessing them using dot notation (<code>self.type</code>), so there's no ambiguity:</p> <pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class Foo(object): ... type = 'abc' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.type 'abc' &gt;&gt;&gt; class Bar(object): ... complex = 123+4j ... &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.complex (123+4j) &gt;&gt;&gt; </code></pre>
4
2009-09-18T18:19:44Z
[ "python", "django", "idioms" ]
Passing Python Data to JavaScript via Django
1,445,989
<p>I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?</p> <p>Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.</p> <p>I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.</p> <p>I'm not (yet) using a JavaScript library like jQuery.</p>
39
2009-09-18T17:52:53Z
1,446,060
<p>It is suboptimal. Have you considered passing your data as JSON using django's built in serializer for that?</p>
2
2009-09-18T18:06:58Z
[ "javascript", "python", "django" ]
Passing Python Data to JavaScript via Django
1,445,989
<p>I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?</p> <p>Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.</p> <p>I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.</p> <p>I'm not (yet) using a JavaScript library like jQuery.</p>
39
2009-09-18T17:52:53Z
1,446,136
<p>You can include <code>&lt;script&gt;</code> tags inside your .html templates, and then build your data structures however is convenient for you. The template language isn't only for HTML, it can also do Javascript object literals.</p> <p>And Paul is right: it might be best to use a json module to create a JSON string, then insert that string into the template. That will handle the quoting issues best, and deal with deep structures with ease.</p>
3
2009-09-18T18:19:57Z
[ "javascript", "python", "django" ]
Passing Python Data to JavaScript via Django
1,445,989
<p>I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?</p> <p>Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.</p> <p>I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.</p> <p>I'm not (yet) using a JavaScript library like jQuery.</p>
39
2009-09-18T17:52:53Z
1,446,170
<p>I recommend against putting much JavaScript in your Django templates - it tends to be hard to write and debug, particularly as your project expands. Instead, try writing all of your JavaScript in a separate script file which your template loads and simply including just a JSON data object in the template. This allows you to do things like run your entire JavaScript app through something like <a href="http://www.jslint.com">JSLint</a>, minify it, etc. and you can test it with a static HTML file without any dependencies on your Django app. Using a library like simplejson also saves you the time spent writing tedious serialization code.</p> <p>If you aren't assuming that you're building an AJAX app this might simply be done like this:</p> <p>In the view:</p> <pre><code>from django.utils import simplejson def view(request, …): js_data = simplejson.dumps(my_dict) … render_template_to_response("my_template.html", {"my_data": js_data, …}) </code></pre> <p>In the template:</p> <pre><code>&lt;script type="text/javascript"&gt; data_from_django = {{ my_data }}; widget.init(data_from_django); &lt;/script&gt; </code></pre> <p>Note that the type of data matters: if <code>my_data</code> is a simple number or a string from a controlled source which doesn't contain HTML, such as a formatted date, no special handling is required. If it's possible to have untrusted data provided by a user you will need to sanitize it using something like the <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape">escape</a> or <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs">escapejs</a> filters and ensure that your JavaScript handles the data safely to avoid <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a> attacks. </p> <p>As far as dates go, you might also want to think about how you pass dates around. I've almost always found it easiest to pass them as Unix timestamps:</p> <p>In Django:</p> <pre><code>time_t = time.mktime(my_date.timetuple()) </code></pre> <p>In JavaScript, assuming you've done something like <code>time_t = {{ time_t }}</code> with the results of the snippet above:</p> <pre><code>my_date = new Date(); my_date.setTime(time_t*1000); </code></pre> <p>Finally, pay attention to UTC - you'll want to have the Python and Django date functions exchange data in UTC to avoid embarrassing shifts from the user's local time.</p> <p>EDIT : Note that the setTime in javascript is in millisecond whereas the output of time.mktime is seconds. That's why we need to multiply by 1000</p>
58
2009-09-18T18:26:20Z
[ "javascript", "python", "django" ]
Passing Python Data to JavaScript via Django
1,445,989
<p>I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?</p> <p>Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.</p> <p>I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.</p> <p>I'm not (yet) using a JavaScript library like jQuery.</p>
39
2009-09-18T17:52:53Z
1,446,959
<p>See the related response to <a href="http://stackoverflow.com/questions/683462/best-way-to-integrate-python-and-javascript/683928#683928">this question</a>. One option is to use <a href="http://jsonpickle.googlecode.com/svn/docs/index.html" rel="nofollow">jsonpickle</a> to serialize between Python objects and JSON/Javascript objects. It wraps simplejson and handles things that are typically not accepted by simplejson.</p>
0
2009-09-18T21:41:01Z
[ "javascript", "python", "django" ]
Passing Python Data to JavaScript via Django
1,445,989
<p>I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?</p> <p>Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.</p> <p>I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.</p> <p>I'm not (yet) using a JavaScript library like jQuery.</p>
39
2009-09-18T17:52:53Z
1,448,178
<p>Putting Java Script embedded into Django template is <strong>rather</strong> always bad idea. </p> <p><strong>Rather</strong>, because there are some exceptions from this rule.</p> <p>Everything depends on the your Java Script code site and functionality.</p> <p>It is better to have seperately static files, like JS, but the problem is that every seperate file needs another connect/GET/request/response mechanism. Sometimes for small one, two liners code os JS to put this into template, bun then use django templatetags mechanism - you can use is in other templates ;)</p> <p>About objects - the same. If your site has AJAX construction/web2.0 like favour - you can achieve very good effect putting some count/math operation onto client side. If objects are small - embedded into template, if large - response them in another connection to avoid hangind page for user.</p>
1
2009-09-19T08:47:57Z
[ "javascript", "python", "django" ]
Passing Python Data to JavaScript via Django
1,445,989
<p>I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it?</p> <p>Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML.</p> <p>I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place.</p> <p>I'm not (yet) using a JavaScript library like jQuery.</p>
39
2009-09-18T17:52:53Z
13,297,018
<p>For anyone who might be having a problems with this, be sure you are rendering your json object under safe mode in the template. You can manually set this like this</p> <pre><code>&lt;script type="text/javascript"&gt; data_from_django = {{ my_data|safe }}; widget.init(data_from_django); &lt;/script&gt; </code></pre>
24
2012-11-08T20:13:26Z
[ "javascript", "python", "django" ]
Python 2.6 send connection object over Queue / Pipe / etc
1,446,004
<p>Given <a href="http://bugs.python.org/issue4892">this bug (Python Issue 4892)</a> that gives rise to the following error:</p> <pre><code>&gt;&gt;&gt; import multiprocessing &gt;&gt;&gt; multiprocessing.allow_connection_pickling() &gt;&gt;&gt; q = multiprocessing.Queue() &gt;&gt;&gt; p = multiprocessing.Pipe() &gt;&gt;&gt; q.put(p) &gt;&gt;&gt; q.get() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/.../python2.6/multiprocessing/queues.py", line 91, in get res = self._recv() TypeError: Required argument 'handle' (pos 1) not found </code></pre> <p>Does anyone know of a workaround to pass a Connection object on a Queue?</p> <p>Thank you.</p>
11
2009-09-18T17:55:30Z
1,446,407
<p>Here's roughly what I did:</p> <pre><code># Producer from multiprocessing.reduction import reduce_connection from multiprocessing import Pipe # Producer and Consumer share the Queue we call queue def handle(queue): reader, writer = Pipe() pickled_writer = pickle.dumps(reduce_connection(writer)) queue.put(pickled_writer) </code></pre> <p>and</p> <pre><code># Consumer from multiprocessing.reduction import rebuild_connection def wait_for_request(): pickled_write = queue.get(block=True) # block=True isn't necessary, of course upw = pickle.loads(pickled_writer) # unpickled writer writer = upw[0](upw[1][0],upw[1][1],upw[1][2]) </code></pre> <p>The last line is cryptic, coming from the following:</p> <pre><code>&gt;&gt;&gt; upw (&lt;function rebuild_connection at 0x1005df140&gt;, (('/var/folders/.../pymp-VhT3wX/listener-FKMB0W', 17, False), True, True)) </code></pre> <p>Hope that helps someone else. It works fine for me.</p>
7
2009-09-18T19:20:09Z
[ "python", "queue", "multiprocessing", "pipe", "pickle" ]
Python 2.6 send connection object over Queue / Pipe / etc
1,446,004
<p>Given <a href="http://bugs.python.org/issue4892">this bug (Python Issue 4892)</a> that gives rise to the following error:</p> <pre><code>&gt;&gt;&gt; import multiprocessing &gt;&gt;&gt; multiprocessing.allow_connection_pickling() &gt;&gt;&gt; q = multiprocessing.Queue() &gt;&gt;&gt; p = multiprocessing.Pipe() &gt;&gt;&gt; q.put(p) &gt;&gt;&gt; q.get() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/.../python2.6/multiprocessing/queues.py", line 91, in get res = self._recv() TypeError: Required argument 'handle' (pos 1) not found </code></pre> <p>Does anyone know of a workaround to pass a Connection object on a Queue?</p> <p>Thank you.</p>
11
2009-09-18T17:55:30Z
4,719,933
<p>(What I believe is) A better method, after some playing around (I was having the same problem. Wanted to pass a pipe through a pipe.) before discovering this post:</p> <pre><code>&gt;&gt;&gt; from multiprocessing import Pipe, reduction &gt;&gt;&gt; i, o = Pipe() &gt;&gt;&gt; reduced = reduction.reduce_connection(i) &gt;&gt;&gt; newi = reduced[0](*reduced[1]) &gt;&gt;&gt; newi.send("hi") &gt;&gt;&gt; o.recv() 'hi' </code></pre> <p>I'm not entirely sure why this is built this way (someone would need insight into what the heck the reduction part of multiprocessing is about for that) but it does definitely work, and requires no pickle import. Other than that, it's pretty close to the above in what it does, but simpler. I also threw this into the python bug report so others know of the workaround.</p>
8
2011-01-18T02:24:23Z
[ "python", "queue", "multiprocessing", "pipe", "pickle" ]
Python cmd module command aliases
1,446,137
<p>I am making a command line interface in Python 3.1.1 using the cmd module.</p> <p>Is there a way to create a command with more than one name e.g. "quit" and "exit"? Or would it just be a case of making a number of commands that all reference the same function?</p>
2
2009-09-18T18:20:09Z
1,446,164
<p>Yes, it would just be a case of making a number of commands that all reference the same function.</p> <p>This is common. It often helps to provide multiple common aliases for a command. It makes the user's life simpler because the odds of them guessing correctly are improved.</p>
4
2009-09-18T18:24:09Z
[ "python", "cmd", "command-line-interface" ]
Can Unittest in Python run a list made of strings?
1,446,317
<p>I am using Selenium to run tests on a website. I have many individual test I need to run, and want to create a script that will run all of the python files in a certain folder. I can get the names, and import the modules, but once I do this I can't get the unittest to run the files. Here is some of the test code I have created. My problem seems to be that once I glob the names they are input as strings, and I can't get away from it.</p> <p>I want to write one of these files for each folder, or some way of executing all of the folders in a directory. Here is the code I have so far:</p> <pre><code>\## This Module will execute all of the Admin&gt;Vehicles&gt;Add Vehicle (AVHC) Test Cases import sys, glob, unittest sys.path.append('/com/inthinc/python/tiwiPro/IE7/AVHC') AddVehicle_IE7_tests = glob.glob('/com/inthinc/python/tiwipro/IE7/AVHC/*.py') for i in range( len(AddVehicle_IE7_tests) ): replaceme = AddVehicle_IE7_tests[i] withoutpy = replaceme.replace( '.py', '') withouttree1 = withoutpy.replace( '/com/inthinc/python/tiwipro/IE7/AVHC\\', '' ) exec("import " + withouttree1) AddVehicle_IE7_tests[i] = withouttree1 sys.path.append('/com/inthinc/python/tiwiPro/FF3/AVHC') AddVehicle_FF3_tests = glob.glob('/com/inthinc/python/tiwipro/FF3/AVHC/*.py') for i in range( len(AddVehicle_FF3_tests) ): replaceme = AddVehicle_FF3_tests[i] withoutpy = replaceme.replace( '.py', '') withouttree2 = withoutpy.replace( '/com/inthinc/python/tiwipro/FF3/AVHC\\', '' ) exec("import " + withouttree2) print withouttree2 if __name__ == '__main__': print AddVehicle_IE7_tests unittest.TextTestRunner().run(AddVehicle_IE7_tests) else: unittest.TextTestRunner().run(AddVehicle_IE7_tests) unittest.TextTestRunner().run(AddVehicle_FF3_tests) print "success" </code></pre>
0
2009-09-18T18:58:58Z
1,844,689
<p>Although I wouldn't exactly recommend this approach (nor probably what you're trying to do), here's a simple approach that appears to accomplish roughly what you want.</p> <p>In file "runner.py" (for example, similar to your above): import glob import unittest</p> <pre><code>testfiles = glob.glob('subdir/*.py') for name in testfiles: execfile(name) if __name__ == '__main__': unittest.main() </code></pre> <p>In file subdir/file1.py:</p> <pre><code>class ClassA(unittest.TestCase): def test01(self): print self </code></pre> <p>In file subdir/file2.py:</p> <pre><code>class ClassB(unittest.TestCase): def test01(self): print self </code></pre> <p>Output when you run "runner.py":</p> <pre><code>C:\svn\stackoverflow&gt;runner test01 (__main__.ClassA) .test01 (__main__.ClassB) . ---------------------------------------------------------------------- Ran 2 tests in 0.004s OK </code></pre> <p>Note that this is basically equivalent to textually including all the test files in the main file, similar to how #include "file.h" works in C. As you can see, the environment (namespace) for the sub-files is that of the file in which execfile() is called, which is why they don't even need to do their own "import unittest" calls. That should be okay if they never need to be run standalone, or you could just include the usual unittest boilerplate in each file if they do need to work on their own. You couldn't have duplicate class names anywhere in the included files, and you may notice other difficulties.</p> <p>I'm pretty sure, however, that you'd be better off using something like <a href="http://code.google.com/p/python-nose/" rel="nofollow">nose</a> or <a href="http://codespeak.net/py/dist/test/" rel="nofollow">py.test</a> which do this sort of "test collection" much better than unittest.</p>
0
2009-12-04T03:39:54Z
[ "python", "selenium-rc" ]
Can Unittest in Python run a list made of strings?
1,446,317
<p>I am using Selenium to run tests on a website. I have many individual test I need to run, and want to create a script that will run all of the python files in a certain folder. I can get the names, and import the modules, but once I do this I can't get the unittest to run the files. Here is some of the test code I have created. My problem seems to be that once I glob the names they are input as strings, and I can't get away from it.</p> <p>I want to write one of these files for each folder, or some way of executing all of the folders in a directory. Here is the code I have so far:</p> <pre><code>\## This Module will execute all of the Admin&gt;Vehicles&gt;Add Vehicle (AVHC) Test Cases import sys, glob, unittest sys.path.append('/com/inthinc/python/tiwiPro/IE7/AVHC') AddVehicle_IE7_tests = glob.glob('/com/inthinc/python/tiwipro/IE7/AVHC/*.py') for i in range( len(AddVehicle_IE7_tests) ): replaceme = AddVehicle_IE7_tests[i] withoutpy = replaceme.replace( '.py', '') withouttree1 = withoutpy.replace( '/com/inthinc/python/tiwipro/IE7/AVHC\\', '' ) exec("import " + withouttree1) AddVehicle_IE7_tests[i] = withouttree1 sys.path.append('/com/inthinc/python/tiwiPro/FF3/AVHC') AddVehicle_FF3_tests = glob.glob('/com/inthinc/python/tiwipro/FF3/AVHC/*.py') for i in range( len(AddVehicle_FF3_tests) ): replaceme = AddVehicle_FF3_tests[i] withoutpy = replaceme.replace( '.py', '') withouttree2 = withoutpy.replace( '/com/inthinc/python/tiwipro/FF3/AVHC\\', '' ) exec("import " + withouttree2) print withouttree2 if __name__ == '__main__': print AddVehicle_IE7_tests unittest.TextTestRunner().run(AddVehicle_IE7_tests) else: unittest.TextTestRunner().run(AddVehicle_IE7_tests) unittest.TextTestRunner().run(AddVehicle_FF3_tests) print "success" </code></pre>
0
2009-09-18T18:58:58Z
1,848,461
<pre><code>## This will execute the tests we need to run import sys, glob, os, time def run_all_tests(): sys.path.append('/com/inthinc/python/tiwiPro/usedbyall/run files') run_all_tests = glob.glob('/com/inthinc/python/tiwipro/usedbyall/run files/*.py') for i in range( len(run_all_tests) ): replaceme = run_all_tests[i] withoutpy = replaceme.replace( '.py', '') withouttree = withoutpy.replace( '/com/inthinc/python/tiwipro/usedbyall/run files\\', '' ) exec("import " + withouttree) exec( withouttree + ".run_test()" ) if __name__ == '__main__': os.system( "taskkill /im java.exe" ) if __name__ == '__main__': os.startfile( "C:/com/inthinc/python/tiwiPro/usedbyall/start_selenium.bat" ) time.sleep( 10 ) run_all_tests() </code></pre> <p>This is what I ended up using. I simply added the run_test() method to each test so I can call them externally like a regular method. This works perfectly, and gives me more control of the test. Also I added a short line that will open the selenium RC server, and close it afterwards.</p>
0
2009-12-04T17:28:11Z
[ "python", "selenium-rc" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
1,446,378
<p>65535 is UCS-2:</p> <blockquote> <p><a href="http://en.wikipedia.org/wiki/UTF-16/UCS-2" rel="nofollow">Thus code point U+0000 is encoded as the number 0, and U+FFFF is encoded as 65535 (which is FFFF16 in hexadecimal).</a></p> </blockquote>
0
2009-09-18T19:14:20Z
[ "python", "unicode", "ucs2" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
1,446,411
<p>It's 0xFFFF (or 65535) for UCS-2, and 0x10FFFF (or 1114111) for UCS-4:</p> <pre><code>Py_UNICODE PyUnicode_GetMax(void) { #ifdef Py_UNICODE_WIDE return 0x10FFFF; #else /* This is actually an illegal character, so it should not be passed to unichr. */ return 0xFFFF; #endif } </code></pre> <p>The maximum character in UCS-4 mode is defined by the maxmimum value representable in UTF-16.</p>
17
2009-09-18T19:20:44Z
[ "python", "unicode", "ucs2" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
1,446,456
<p>When built with --enable-unicode=ucs4:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.maxunicode 1114111 </code></pre> <p>When built with --enable-unicode=ucs2:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.maxunicode 65535 </code></pre>
79
2009-09-18T19:33:45Z
[ "python", "unicode", "ucs2" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
1,450,155
<p>I had this same issue once. I documented it for myself on my wiki at</p> <p><a href="http://arcoleo.org/dsawiki/Wiki.jsp?page=Python%20UTF%20-%20UCS2%20or%20UCS4">http://arcoleo.org/dsawiki/Wiki.jsp?page=Python%20UTF%20-%20UCS2%20or%20UCS4</a></p> <p>I wrote -</p> <pre><code>import sys sys.maxunicode &gt; 65536 and 'UCS4' or 'UCS2' </code></pre>
9
2009-09-20T02:50:11Z
[ "python", "unicode", "ucs2" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
35,801,395
<p><a href="https://docs.python.org/2.7/library/sysconfig.html" rel="nofollow">sysconfig</a> will tell the unicode size from the configuration variables of python.</p> <p>The buildflags can be queried like this.</p> <p><strong>Python 2.7:</strong></p> <pre><code>import sysconfig sysconfig.get_config_var('Py_UNICODE_SIZE') </code></pre> <p><strong>Python 2.6:</strong></p> <pre><code>import distutils distutils.sysconfig.get_config_var('Py_UNICODE_SIZE') </code></pre>
3
2016-03-04T16:40:42Z
[ "python", "unicode", "ucs2" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
38,990,558
<p>I had the same issue and found a semi-official piece of code that does exactly that and may be interesting for people with the same issue: <a href="https://bitbucket.org/pypa/wheel/src/cf4e2d98ecb1f168c50a6de496959b4a10c6b122/wheel/pep425tags.py?at=default&amp;fileviewer=file-view-default#pep425tags.py-83:89" rel="nofollow">https://bitbucket.org/pypa/wheel/src/cf4e2d98ecb1f168c50a6de496959b4a10c6b122/wheel/pep425tags.py?at=default&amp;fileviewer=file-view-default#pep425tags.py-83:89</a>.</p> <p>It comes from the wheel project which needs to check if the python is compiled with ucs-2 or ucs-4 because it will change the name of the binary file generated.</p>
0
2016-08-17T07:28:02Z
[ "python", "unicode", "ucs2" ]
How to find out if Python is compiled with UCS-2 or UCS-4?
1,446,347
<p>Just what the title says.</p> <pre><code>$ ./configure --help | grep -i ucs --enable-unicode[=ucs[24]] </code></pre> <p>Searching the official documentation, I found this:</p> <blockquote> <p><strong><a href="http://docs.python.org/3.1/library/sys.html#sys.maxunicode">sys.maxunicode</a></strong>: An integer giving the largest supported code point for a Unicode character. The <strong>value</strong> of this depends on the configuration option that specifies whether Unicode characters are stored as UCS-2 or UCS-4.</p> </blockquote> <p>What is not clear here is - which value(s) correspond to UCS-2 and UCS-4.</p> <p>The code is expected to work on Python 2.6+.</p>
45
2009-09-18T19:06:49Z
39,368,698
<p>Another way is to create an Unicode array and look at the itemsize:</p> <pre><code>import array bytes_per_char = array.array('u').itemsize </code></pre> <p>Quote from the <a href="https://docs.python.org/2/library/array.html" rel="nofollow"><code>array</code> docs</a>:</p> <blockquote> <p>The <code>'u'</code> typecode corresponds to Python’s unicode character. On narrow Unicode builds this is 2-bytes, on wide builds this is 4-bytes.</p> </blockquote> <p>Note that the distinction between narrow and wide Unicode builds is dropped from Python 3.3 onward, see <a href="https://www.python.org/dev/peps/pep-0393/" rel="nofollow">PEP393</a>. The <code>'u'</code> typecode for <code>array</code> is deprecated since 3.3 and scheduled for removal in Python 4.0.</p>
1
2016-09-07T11:28:30Z
[ "python", "unicode", "ucs2" ]
Clutter does not update screen outside of breakpoints
1,446,554
<p>I have some code:</p> <pre><code>l1 = clutter.Label() l1.set_position(100,100) for i in range(0,10): l1.set_text(str(i)) time.sleep(1) </code></pre> <p>That is designed to show a count from 1 to 10 seconds on the screen in clutter, but I'm getting a strange error. When I run the script normally the screen runs as it should do, but there is no text displayed until 10 seconds are up. However, When I run with breakpoints in pdb the text shows up just fine.</p> <p>I'm also getting a strange error at the start of the program:</p> <pre><code>do_wait: drmWaitVBlank returned -1, IRQs don't seem to be working correctly. Try adjusting the vlank_mode configuration parameter. </code></pre> <p>But I don't see why that would affect the code out of break points but not in breakpoints.</p> <p>Any help would be greatly appreciated.</p>
0
2009-09-18T20:01:49Z
1,447,692
<p>Have you tried <a href="http://www.clutter-project.org/contribute.html" rel="nofollow">posting</a> (or <a href="http://lists.o-hand.com/clutter/" rel="nofollow">searching</a>) on the Clutter mailing list? <a href="http://lists.o-hand.com/clutter/1167.html" rel="nofollow">Here</a>'s someone who got the same message about drmWaitVBlank for example.</p> <p>My guess is most people on SO wouldn't be familiar with solving Clutter problems. I know I'm not <code>:)</code></p>
0
2009-09-19T03:56:10Z
[ "python", "linux", "graphics", "clutter-gui" ]
Clutter does not update screen outside of breakpoints
1,446,554
<p>I have some code:</p> <pre><code>l1 = clutter.Label() l1.set_position(100,100) for i in range(0,10): l1.set_text(str(i)) time.sleep(1) </code></pre> <p>That is designed to show a count from 1 to 10 seconds on the screen in clutter, but I'm getting a strange error. When I run the script normally the screen runs as it should do, but there is no text displayed until 10 seconds are up. However, When I run with breakpoints in pdb the text shows up just fine.</p> <p>I'm also getting a strange error at the start of the program:</p> <pre><code>do_wait: drmWaitVBlank returned -1, IRQs don't seem to be working correctly. Try adjusting the vlank_mode configuration parameter. </code></pre> <p>But I don't see why that would affect the code out of break points but not in breakpoints.</p> <p>Any help would be greatly appreciated.</p>
0
2009-09-18T20:01:49Z
1,982,896
<p>Not sure if you've already figured out the answer to this but:</p> <p>The reason you are having this problem is because you are blocking the main thread (where all the drawing occurs) with your time.sleep() calls, preventing the library from redrawing the screen.</p> <p>E.g. your code is currently doing this:</p> <ol> <li>Clutter redraws the screen.</li> <li>You loop over ten seconds and change the text ten times.</li> <li>Clutter redraws the screen.</li> </ol> <p>If you want to queue something on a timer, you should look into <a href="http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add" rel="nofollow">gobject.timeout_add</a>.</p>
4
2009-12-30T22:35:11Z
[ "python", "linux", "graphics", "clutter-gui" ]
Python decorator to ensure that kwargs are correct
1,446,555
<p>I have done a decorator that I used to ensure that the keyword arguments passed to a constructor are the <strong>correct/expected ones</strong>. The code is the following: <code></p> <pre><code>from functools import wraps def keyargs_check(keywords): """ This decorator ensures that the keys passed in kwargs are the onces that are specified in the passed tuple. When applied this decorate will check the keywords and will throw an exception if the developer used one that is not recognized. @type keywords: tuple @param keywords: A tuple with all the keywords recognized by the function. """ def wrap(f): @wraps(f) def newFunction(*args, **kw): # we are going to add an extra check in kw for current_key in kw.keys(): if not current_key in keywords: raise ValueError( "The key {0} is a not recognized parameters by {1}.".format( current_key, f.__name__)) return f(*args, **kw) return newFunction return wrap </code></pre> <p></code> An example use of this decorator would be the following: <code></p> <pre><code>class Person(object): @keyargs_check(("name", "surname", "age")) def __init__(self, **kwargs): # perform init according to args </code></pre> <p></code> Using the above code if the developer passes a key args like "blah" it will <strong>throw an exception</strong>. Unfortunately my implementation has a major problem with inheritance, if I define the following: <code></p> <pre><code>class PersonTest(Person): @keyargs_check(("test")) def __init__(self, **kwargs): Person.__init__(self,**kwargs) </code></pre> <p></code></p> <p>Because I'm passing kwargs to the super class init method, I'm going to get an exception because "test" <strong>is not in the tuple</strong> passed to the decorator of the super class. Is there a way to let the decorator used in the super class to know about the extra keywords? or event better, is there a standard way to achieve what I want?</p> <p>Update: I am more interested in automate the way I throw an exception when a developer passes the wrong kwarg rather than on the fact that I use kwargs instead of args. What I mean is, I do not want have to write the code that check the args passed to the method in every class.</p>
2
2009-09-18T20:01:57Z
1,446,657
<p>Your decorator is not necessary. The only thing the decorator does that can't be done with the standard syntax is prevent keyword args from absorbing positional arguments. Thus</p> <pre><code>class Base(object): def __init__(name=None,surname=None,age=None): #some code class Child(Base): def __init__(test=None,**kwargs): Base.__init__(self,**kwargs) </code></pre> <p>The advantage of this is that <code>kwargs</code> in <code>Child</code> will not contain <code>test</code>. The problem is that you can muck it up with a call like <code>c = Child('red herring')</code>. This is <a href="http://www.python.org/dev/peps/pep-3102/" rel="nofollow">fixed in python 3.0</a>.</p> <p>The problem with your approach is that you're trying to use a decorator to do a macro's job, which is unpythonic. The only thing that will get you what you want is something that modifies the locals of the innermost function (<code>f</code> in your code, specifically the <code>kwargs</code> variable). How should your decorator know the wrapper's insides, how would it know that it calls a superclass?</p>
4
2009-09-18T20:26:48Z
[ "python" ]
How to make easy_install execute custom commands in setup.py?
1,446,682
<p>I want my setup.py to do some custom actions besides just installing the Python package (like installing an init.d script, creating directories and files, etc.) I know I can customize the distutils/setuptools classes to do my own actions. The problem I am having is that everything works when I cd to the package directory and do "python setup.py install", but my custom classes don't seem to be executed when I do "easy_install mypackage.tar.gz". Here's my setup.py file (create an empty myfoobar.py file in the same dir to test):</p> <pre><code>import setuptools from setuptools.command import install as _install class install(_install.install): def initialize_options(self): _install.install.initialize_options(self) def finalize_options(self): _install.install.finalize_options(self) def run(self): # Why is this never executed when tarball installed with easy_install? # It does work with: python setup.py install import pdb;pdb.set_trace() _install.install.run(self) setuptools.setup( name = 'myfoobar', version = '0.1', platforms = ['any'], description = 'Test package', author = 'Someone', py_modules = ['myfoobar'], cmdclass = {'install': install}, ) </code></pre> <p>The same thing happens even if I import "setup" and "install" from distutils. Any ideas how I could make easy_install execute my custom classes?</p> <p>To clarify, I don't want to use anything extra, like Buildout or Paver.</p>
7
2009-09-18T20:30:02Z
1,446,925
<p><a href="http://www.blueskyonmars.com/projects/paver/">Paver</a> takes setuptools to the next level and lets you write custom tasks. It allows you to extend the typical setup.py file and provides a simple way to bootstrap the Paver environment.</p>
5
2009-09-18T21:32:05Z
[ "python", "setuptools", "easy-install" ]
How to make easy_install execute custom commands in setup.py?
1,446,682
<p>I want my setup.py to do some custom actions besides just installing the Python package (like installing an init.d script, creating directories and files, etc.) I know I can customize the distutils/setuptools classes to do my own actions. The problem I am having is that everything works when I cd to the package directory and do "python setup.py install", but my custom classes don't seem to be executed when I do "easy_install mypackage.tar.gz". Here's my setup.py file (create an empty myfoobar.py file in the same dir to test):</p> <pre><code>import setuptools from setuptools.command import install as _install class install(_install.install): def initialize_options(self): _install.install.initialize_options(self) def finalize_options(self): _install.install.finalize_options(self) def run(self): # Why is this never executed when tarball installed with easy_install? # It does work with: python setup.py install import pdb;pdb.set_trace() _install.install.run(self) setuptools.setup( name = 'myfoobar', version = '0.1', platforms = ['any'], description = 'Test package', author = 'Someone', py_modules = ['myfoobar'], cmdclass = {'install': install}, ) </code></pre> <p>The same thing happens even if I import "setup" and "install" from distutils. Any ideas how I could make easy_install execute my custom classes?</p> <p>To clarify, I don't want to use anything extra, like Buildout or Paver.</p>
7
2009-09-18T20:30:02Z
1,621,540
<p>It cannot be done. Enthought has a custom version of setuptools that does support this, but otherwise it is in the bug tracker as a wishlist item that has been under discussion since June.</p> <p>However, there are ways to trick the system and you might consider them. One way is to have your most important module, the one that is always imported first when using your package, do the post install actions the first time it is called. Then you have to clean up after yourself, and consider the case where you cannot write into the library because an admin installed the package and the first user is someone other than admin.</p> <p>In the worst case, this would involve creating a ~/.mypackage directory for ever user who uses the package, and rerunning the postinstall once for each new user. Every time the module is imported, it checks for the existence of ~/.mypackage. If it is not there, it runs the postinstall and creates it. If it is there, it skips the postinstall.</p>
4
2009-10-25T17:49:42Z
[ "python", "setuptools", "easy-install" ]
What are good names for user defined exceptions?
1,446,789
<p>This question covers a broad range of programming languages; however, I am specifically working with Python in this case.</p> <p>I would like to create some user defined exceptions, but I'm not sure how fine-grained they should be. For example, if I have the following class:</p> <pre><code>class Race(object): def __init__(self, start_time, end_time): if end_time &lt; start_time: raise WhatToNameThisError self._start_time = start_time self._finish_time = end_time </code></pre> <p>I would like an exception to be raised if the finish time occurs before the start time, but I could I call it?</p> <ul> <li>RaceError (all exceptions related to the Race class can use this, and the message can distinguish between them)</li> <li>RaceFinishTimeBeforeStartTime (more specific, but means I know exactly what I'm catching)</li> </ul> <p>I'm sure there are other ways of looking at this, and thus more options for naming an exception. Are there any standards or guidelines which outline this?</p>
4
2009-09-18T20:52:26Z
1,446,824
<p>I think the built-in ValueError may be appropriate in this case. From the Python docs:</p> <blockquote> <p>exception ValueError</p> <p>Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.</p> </blockquote>
6
2009-09-18T21:01:54Z
[ "python", "exception", "exception-handling" ]
What are good names for user defined exceptions?
1,446,789
<p>This question covers a broad range of programming languages; however, I am specifically working with Python in this case.</p> <p>I would like to create some user defined exceptions, but I'm not sure how fine-grained they should be. For example, if I have the following class:</p> <pre><code>class Race(object): def __init__(self, start_time, end_time): if end_time &lt; start_time: raise WhatToNameThisError self._start_time = start_time self._finish_time = end_time </code></pre> <p>I would like an exception to be raised if the finish time occurs before the start time, but I could I call it?</p> <ul> <li>RaceError (all exceptions related to the Race class can use this, and the message can distinguish between them)</li> <li>RaceFinishTimeBeforeStartTime (more specific, but means I know exactly what I'm catching)</li> </ul> <p>I'm sure there are other ways of looking at this, and thus more options for naming an exception. Are there any standards or guidelines which outline this?</p>
4
2009-09-18T20:52:26Z
1,446,830
<p>I try to use appropriate built-in exceptions as much as possible. In languages like Java and C# the exception list is so robust that you'll rarely find one you need to define yourself. I'm not super-familiar with Python's exception list, but IIRC there are at least a few pretty general good ones.</p>
1
2009-09-18T21:03:41Z
[ "python", "exception", "exception-handling" ]
How to encapsulate python modules?
1,446,852
<p>Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file?</p> <p>My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't have the modules installed. That's why I would like to do this.</p> <p>Sorry if this is a dumb question.</p> <p>edit: Thanks all for your answers. I think the solution for this resolves around virtualenv. Could someone be kind enough to explain me this in very simple terms? I have read the virtualenv page, but still am very confused. Thanks once again.</p>
2
2009-09-18T21:09:49Z
1,446,876
<p>You don't actually have to combine the files, or install them in a system-wide location. Just make sure the libraries are in a directory readable by your Python script (and therefore, by your PHP app) and added to the Python load path.</p> <p>The Python runtime searches for libraries in the directories in the <code>sys.path</code> array. You can add directories to that array at runtime using the <code>PYTHONPATH</code> environment variable, or by explicitly appending items to <code>sys.path</code>. The code snippet below, added to a Python script, adds the directory in which the script is located to the search path, implicitly making any libraries located in the same place available for import:</p> <pre><code>import os, sys sys.path.append(os.path.dirname(__file__)) </code></pre>
4
2009-09-18T21:17:35Z
[ "python", "encapsulation" ]
How to encapsulate python modules?
1,446,852
<p>Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file?</p> <p>My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't have the modules installed. That's why I would like to do this.</p> <p>Sorry if this is a dumb question.</p> <p>edit: Thanks all for your answers. I think the solution for this resolves around virtualenv. Could someone be kind enough to explain me this in very simple terms? I have read the virtualenv page, but still am very confused. Thanks once again.</p>
2
2009-09-18T21:09:49Z
1,446,968
<p>Check out virtualenv, to create a local python installation, where you can install BeautifulSoup and all other libraries you want.</p> <p><a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">http://pypi.python.org/pypi/virtualenv</a></p>
2
2009-09-18T21:43:36Z
[ "python", "encapsulation" ]
How to encapsulate python modules?
1,446,852
<p>Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file?</p> <p>My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't have the modules installed. That's why I would like to do this.</p> <p>Sorry if this is a dumb question.</p> <p>edit: Thanks all for your answers. I think the solution for this resolves around virtualenv. Could someone be kind enough to explain me this in very simple terms? I have read the virtualenv page, but still am very confused. Thanks once again.</p>
2
2009-09-18T21:09:49Z
1,446,977
<p>No, you can't (in general), because doing so would destroy the module searching method that python uses (files and directories). I guess that you could, with some hack, generate a module hierarchy without having the actual filesystem layout, but this is a huge hack, probably something like</p> <pre><code>&gt;&gt;&gt; sha=types.ModuleType("sha") &gt;&gt;&gt; sha &lt;module 'sha' (built-in)&gt; ['__doc__', '__name__'] &gt;&gt;&gt; sha.foo=3 &gt;&gt;&gt; sha.zam=types.ModuleType("zam") &gt;&gt;&gt; sha.foo 3 &gt;&gt;&gt; dir(sha) ['__doc__', '__name__', 'foo', 'zam'] </code></pre> <p>But in any case you would have to generate the code that creates this layout and stores the stuff into properly named identifiers.</p> <p>What you need is probably to learn to use .egg files. They are unique agglomerated entities containing your library, like .jar files.</p>
0
2009-09-18T21:48:04Z
[ "python", "encapsulation" ]
Help with Python in the web
1,447,010
<p>I've been using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> to make WSGI compliant applications. I'm trying to modify the code in the front page.</p> <p>Its basic idea is that you go to the /hello URL and you get a "Hello World!" message. You go to /hello/ and you get "hello !". For example, /hello/jeff yields "Hello Jeff!". Anyway, what I'm trying to do is putting a form in the front page with a text box where you can enter your name, and it will submit it to /hello. So if you enter "Jeff" in the form and submit, you get the "Hello Jeff!" message.</p> <p>However, I have no idea how to do this. I need to pass the "name" variable to the hello template, but I don't know how. Here's my index.html:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Index page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Go to the &lt;a href="${url_for('say_hello')}"&gt;default&lt;/a&gt;&lt;/h1&gt; &lt;form name="helloform" action="${url_for('say_hello')}" method="post"&gt; &lt;input type="text" name="name"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>method="get" doesn't work either, predictably.</p>
0
2009-09-18T21:59:03Z
1,447,101
<p>Directly on the page link to which you provide (<a href="http://werkzeug.pocoo.org/" rel="nofollow">http://werkzeug.pocoo.org/</a>) when clicking on 'Click here', you get a code for the hello X example. What you seem to be missing is:</p> <pre><code>Hello ${url_values['name']|h}! </code></pre> <p>somewhere in your html template (assuming it is the template for response as well as for request)</p>
-1
2009-09-18T22:31:30Z
[ "python", "wsgi", "werkzeug" ]
Help with Python in the web
1,447,010
<p>I've been using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> to make WSGI compliant applications. I'm trying to modify the code in the front page.</p> <p>Its basic idea is that you go to the /hello URL and you get a "Hello World!" message. You go to /hello/ and you get "hello !". For example, /hello/jeff yields "Hello Jeff!". Anyway, what I'm trying to do is putting a form in the front page with a text box where you can enter your name, and it will submit it to /hello. So if you enter "Jeff" in the form and submit, you get the "Hello Jeff!" message.</p> <p>However, I have no idea how to do this. I need to pass the "name" variable to the hello template, but I don't know how. Here's my index.html:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Index page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Go to the &lt;a href="${url_for('say_hello')}"&gt;default&lt;/a&gt;&lt;/h1&gt; &lt;form name="helloform" action="${url_for('say_hello')}" method="post"&gt; &lt;input type="text" name="name"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>method="get" doesn't work either, predictably.</p>
0
2009-09-18T21:59:03Z
1,447,174
<p>HTML Forms have a static target address, <code>action="/something"</code>, but you want to <em>change the address depending user input</em>. You have two options: </p> <ol> <li><p>Add javascript to the html form to change the target address (by appending the name) before the form is submitted.</p></li> <li><p>Write a new method in your web framework that reads GET or POST variables and point the form there.</p></li> </ol>
0
2009-09-18T23:03:11Z
[ "python", "wsgi", "werkzeug" ]
Help with Python in the web
1,447,010
<p>I've been using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> to make WSGI compliant applications. I'm trying to modify the code in the front page.</p> <p>Its basic idea is that you go to the /hello URL and you get a "Hello World!" message. You go to /hello/ and you get "hello !". For example, /hello/jeff yields "Hello Jeff!". Anyway, what I'm trying to do is putting a form in the front page with a text box where you can enter your name, and it will submit it to /hello. So if you enter "Jeff" in the form and submit, you get the "Hello Jeff!" message.</p> <p>However, I have no idea how to do this. I need to pass the "name" variable to the hello template, but I don't know how. Here's my index.html:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Index page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Go to the &lt;a href="${url_for('say_hello')}"&gt;default&lt;/a&gt;&lt;/h1&gt; &lt;form name="helloform" action="${url_for('say_hello')}" method="post"&gt; &lt;input type="text" name="name"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>method="get" doesn't work either, predictably.</p>
0
2009-09-18T21:59:03Z
1,447,221
<p>HTML is based on the REST principle... each url should be an object, like a person; NOT an action, like saying hello to a person. Have the URL identify who you want to greet only if your web application knows who that is internally, by looking at its database.</p> <p>If your webapplication has no object called Joe, then designing URLs with Joe in them is not the right approach. Your particular web application is about finding out who people are and sending a hello messages to them. So, you should probably have one URL: /greeter, which looks for information sent in GET or POST requests (from your form), and displays a greeting. If it doesn't know who to greet, it can display the form to find out.</p> <p>Always think in terms of the objects you're actually working with --- the components that make up the system --- when building software.</p>
-1
2009-09-18T23:31:56Z
[ "python", "wsgi", "werkzeug" ]
Help with Python in the web
1,447,010
<p>I've been using <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a> to make WSGI compliant applications. I'm trying to modify the code in the front page.</p> <p>Its basic idea is that you go to the /hello URL and you get a "Hello World!" message. You go to /hello/ and you get "hello !". For example, /hello/jeff yields "Hello Jeff!". Anyway, what I'm trying to do is putting a form in the front page with a text box where you can enter your name, and it will submit it to /hello. So if you enter "Jeff" in the form and submit, you get the "Hello Jeff!" message.</p> <p>However, I have no idea how to do this. I need to pass the "name" variable to the hello template, but I don't know how. Here's my index.html:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Index page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Go to the &lt;a href="${url_for('say_hello')}"&gt;default&lt;/a&gt;&lt;/h1&gt; &lt;form name="helloform" action="${url_for('say_hello')}" method="post"&gt; &lt;input type="text" name="name"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>method="get" doesn't work either, predictably.</p>
0
2009-09-18T21:59:03Z
1,447,616
<p>Do it the right way: go to <code>/hello?name=joe</code> to say hello to joe, and so forth. That's how HTML/HTTP is <strong>designed</strong> to work! Your code behind the <code>/hello</code> URL just needs to get the <code>name</code> parameter from the request, if present, and respond accordingly.</p>
1
2009-09-19T03:14:15Z
[ "python", "wsgi", "werkzeug" ]
Embed a spreadsheet/table in a PyGTK application?
1,447,187
<p>In my application, we want to present the user with a typical spreadsheet/table (OO.O/Excel-style), and then pull out the values and do something with them internally.</p> <p>Is there a preexisting widget for PyGTK that does this? The <a href="http://faq.pygtk.org/index.py?req=all#19.14" rel="nofollow">PyGTK FAQ</a> mentions <a href="http://www.sicem.biz/personal/lgs/projects/gtkgrid/view%5Fproject" rel="nofollow">GtkGrid</a>, but the link is dead and I can't find a tarball anywhere.</p>
2
2009-09-18T23:10:48Z
1,447,200
<p>It's perhaps a little more manual than, for instance, a GridView in .Net, but the Tree View widget will do what you need and much more. See <a href="http://www.pygtk.org/pygtk2tutorial/ch-TreeViewWidget.html" rel="nofollow">PyGtk TreeView</a></p>
3
2009-09-18T23:17:36Z
[ "python", "pygtk", "spreadsheet" ]
Embed a spreadsheet/table in a PyGTK application?
1,447,187
<p>In my application, we want to present the user with a typical spreadsheet/table (OO.O/Excel-style), and then pull out the values and do something with them internally.</p> <p>Is there a preexisting widget for PyGTK that does this? The <a href="http://faq.pygtk.org/index.py?req=all#19.14" rel="nofollow">PyGTK FAQ</a> mentions <a href="http://www.sicem.biz/personal/lgs/projects/gtkgrid/view%5Fproject" rel="nofollow">GtkGrid</a>, but the link is dead and I can't find a tarball anywhere.</p>
2
2009-09-18T23:10:48Z
1,447,210
<p>You might consider embedding a web page viewer - you can do a lot with that: <a href="http://blog.mypapit.net/2009/09/pymoembed-web-browser-in-python-gtk-application.html" rel="nofollow">http://blog.mypapit.net/2009/09/pymoembed-web-browser-in-python-gtk-application.html</a></p>
0
2009-09-18T23:24:49Z
[ "python", "pygtk", "spreadsheet" ]
Embed a spreadsheet/table in a PyGTK application?
1,447,187
<p>In my application, we want to present the user with a typical spreadsheet/table (OO.O/Excel-style), and then pull out the values and do something with them internally.</p> <p>Is there a preexisting widget for PyGTK that does this? The <a href="http://faq.pygtk.org/index.py?req=all#19.14" rel="nofollow">PyGTK FAQ</a> mentions <a href="http://www.sicem.biz/personal/lgs/projects/gtkgrid/view%5Fproject" rel="nofollow">GtkGrid</a>, but the link is dead and I can't find a tarball anywhere.</p>
2
2009-09-18T23:10:48Z
1,450,766
<p><code>GtkGrid</code> is deprecated in favor of the more powerful and more customizable <a href="http://library.gnome.org/devel/pygtk/stable/class-gtktreeview.html" rel="nofollow"><code>GtkTreeView</code></a>.</p> <p>It can display trees and lists. To make it work like a table, you must define a <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkliststore.html" rel="nofollow"><code>ListStore</code></a> where it will take the data from, and <a href="http://library.gnome.org/devel/pygtk/stable/class-gtktreeviewcolumn.html" rel="nofollow"><code>TreeViewColumn</code></a>s for each column you want to show, with <a href="http://library.gnome.org/devel/pygtk/stable/class-pygtkgenericcellrenderer.html" rel="nofollow"><code>CellRenderer</code></a>s to define how to show the column. This separation of data and render allows you to render other controls on the cell, like text boxes or images.</p> <p><code>GtkTreeView</code> is very flexible, but it seems complex at first because of the many options. To help with that, there's the <a href="http://www.pygtk.org/pygtk2tutorial/ch-TreeViewWidget.html" rel="nofollow">relevant section</a> in the <a href="http://www.pygtk.org/pygtk2tutorial/" rel="nofollow">PyGTK tutorial</a> (although you should read it entirely, not just this section).</p> <p>For completeness, here's an example code and a screenshot of it running in my system:</p> <p><img src="http://i.stack.imgur.com/p4B9Y.png" alt="Screenshot-TreeViewColumn Example.png"></p> <pre><code>#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk class TreeViewColumnExample(object): # close the window and quit def delete_event(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): # Create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("TreeViewColumn Example") self.window.connect("delete_event", self.delete_event) # create a liststore with one string column to use as the model self.liststore = gtk.ListStore(str, str, str, 'gboolean') # create the TreeView using liststore self.treeview = gtk.TreeView(self.liststore) # create the TreeViewColumns to display the data self.tvcolumn = gtk.TreeViewColumn('Pixbuf and Text') self.tvcolumn1 = gtk.TreeViewColumn('Text Only') # add a row with text and a stock item - color strings for # the background self.liststore.append(['Open', gtk.STOCK_OPEN, 'Open a File', True]) self.liststore.append(['New', gtk.STOCK_NEW, 'New File', True]) self.liststore.append(['Print', gtk.STOCK_PRINT, 'Print File', False]) # add columns to treeview self.treeview.append_column(self.tvcolumn) self.treeview.append_column(self.tvcolumn1) # create a CellRenderers to render the data self.cellpb = gtk.CellRendererPixbuf() self.cell = gtk.CellRendererText() self.cell1 = gtk.CellRendererText() # set background color property self.cellpb.set_property('cell-background', 'yellow') self.cell.set_property('cell-background', 'cyan') self.cell1.set_property('cell-background', 'pink') # add the cells to the columns - 2 in the first self.tvcolumn.pack_start(self.cellpb, False) self.tvcolumn.pack_start(self.cell, True) self.tvcolumn1.pack_start(self.cell1, True) self.tvcolumn.set_attributes(self.cellpb, stock_id=1) self.tvcolumn.set_attributes(self.cell, text=0) self.tvcolumn1.set_attributes(self.cell1, text=2, cell_background_set=3) # make treeview searchable self.treeview.set_search_column(0) # Allow sorting on the column self.tvcolumn.set_sort_column_id(0) # Allow drag and drop reordering of rows self.treeview.set_reorderable(True) self.window.add(self.treeview) self.window.show_all() def main(): gtk.main() if __name__ == "__main__": tvcexample = TreeViewColumnExample() main() </code></pre>
12
2009-09-20T10:49:20Z
[ "python", "pygtk", "spreadsheet" ]
How do I partition datetime intervals which overlap (Org Mode clocked time)?
1,447,257
<p>I have related tasks from two Org files/subtrees where some of the clocked time overlaps. These are a manual worklog and a generated git commit log, see below.</p> <p>One subtree's CLOCK: entries needs to be adjusted to remove overlapping time. The other subtree is considered complete, and it's CLOCK: entries should not be adjusted.</p> <p><strong><em>EDIT: This question is about calculating new time intervals to remove any overlaps. Any suggestions don't need to parse the Org mode file format. Python datetime.datetime algorithms are helpful, as are Emacs Lisp with or without the use of Org mode functions.</em></strong></p> <p>In Python (more familiar) or Emacs Lisp (Org functions could help) I would like to:</p> <ol> <li><p>Identify time overlaps where they occur. file1.org will be mutable, file2.org time intervals should be considered fixed/correct.</p></li> <li><p>Calculate new time intervals for the CLOCK: lines in file1.org to remove any overlap with file2.org CLOCK: lines.</p></li> <li><p>write resulting new CLOCK: lines out, or at least the pertinent datetimes.</p></li> </ol> <p>The python convenience function tsparse converts an Org Mode timestamp to a python datetime.datetime object:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; def tsparse(timestring): return datetime.strptime(timestring,'%Y-%m-%d %a %H:%M') &gt;&gt;&gt; tsparse('2008-10-15 Wed 00:45') datetime.datetime(2008, 10, 15, 0, 45) </code></pre> <p>Test cases can be found below. Thanks for any algorithm or implementation suggestions for Python or Emacs Lisp.</p> <p>Jeff</p> <p><hr /></p> <p><strong>file1.org</strong>, <em>prior to</em> adjustments:</p> <pre><code>* Manually Edited Worklog ** DONE Onsite CLOSED: [2009-09-09 Wed 15:00] :LOGBOOK: CLOCK: [2009-09-09 Wed 07:00]--[2009-09-09 Wed 15:00] =&gt; 8:00 :END: ** DONE Onsite CLOSED: [2009-09-10 Wed 15:00] :LOGBOOK: CLOCK: [2009-09-10 Thu 08:00]--[2009-09-10 Thu 15:00] =&gt; 7:00 :END: </code></pre> <p><hr /></p> <p><strong>file2.org</strong>:</p> <pre><code>* Generated commit log ** DONE Commit 1 :partial:overlap:leading:contained: CLOSED: [2009-09-09 Tue 10:18] :LOGBOOK: CLOCK: [2009-09-09 Wed 06:40]--[2009-09-09 Wed 07:18] =&gt; 0:38 CLOCK: [2009-09-09 Wed 10:12]--[2009-09-09 Wed 10:18] =&gt; 0:06 :END: ** DONE Commit 2 :contained:overlap:contiguous: CLOSED: [2009-09-09 Wed 10:20] :LOGBOOK: CLOCK: [2009-09-09 Wed 10:18]--[2009-09-09 Wed 10:20] =&gt; 0:02 :END: ** DONE Commit 4 :contained:overlap: CLOSED: [2009-09-10 Wed 09:53] :LOGBOOK: CLOCK: [2009-09-10 Wed 09:49]--[2009-09-10 Wed 09:53] =&gt; 0:04 :END: ** DONE Commit 5 :partial:overlap:trailing: CLOSED: [2009-09-10 Wed 15:12] :LOGBOOK: CLOCK: [2009-09-10 Wed 14:45]--[2009-09-10 Wed 15:12] =&gt; 0:27 :END: ** DONE Commit 6 :partial:overlap:leading: CLOSED: [2009-09-11 Fri 08:05] :LOGBOOK: CLOCK: [2009-09-11 Fri 07:50]--[2009-09-11 Fri 08:05] =&gt; 0:15 :END: ** DONE Commit 7 :nonoverlap: CLOSED: [2009-09-11 Fri 15:55] :LOGBOOK: CLOCK: [2009-09-11 Fri 15:25]--[2009-09-11 Fri 15:55] =&gt; 0:30 :END: </code></pre> <p><hr /></p> <p><strong>file1.org</strong>, <em>after</em> adjustments:</p> <pre><code>* Manually Edited Worklog ** DONE Onsite CLOSED: [2009-09-09 Wed 15:00] :LOGBOOK: CLOCK: [2009-09-09 Wed 10:20]--[2009-09-09 Wed 14:45] =&gt; 4:25 CLOCK: [2009-09-09 Wed 07:18]--[2009-09-09 Wed 10:12] =&gt; 2:54 :END: ** DONE Onsite CLOSED: [2009-09-10 Wed 15:00] :LOGBOOK: CLOCK: [2009-09-10 Thu 08:05]--[2009-09-10 Thu 15:00] =&gt; 6:55 :END: </code></pre>
2
2009-09-18T23:55:09Z
1,447,648
<p>Do you want help parsing the file format? Or just on figuring out the overlapping times?</p> <p><code>datetime</code> objects are comparable in Python, so you can do something like this:</p> <pre><code>&gt;&gt;&gt; (a,b) = (datetime(2009, 9, 15, 8, 30), datetime(2009, 9, 15, 8, 45)) &gt;&gt;&gt; (c,d) = (datetime(2009, 9, 15, 8, 40), datetime(2009, 9, 15, 8, 50)) &gt;&gt;&gt; a &lt;= b True &gt;&gt;&gt; if c &lt;= b &lt;= d: ... print "overlap, merge these two ranges" ... else: ... print "separate ranges, leave them alone" ... overlap, merge these two ranges </code></pre> <p>If the end of the first range (b) is within the second range (c and d), then there is an overlap and you can merge those two pairs into one range (a,d).</p> <p>Since your set of data looks pretty small you can probably just do this comparison and merge between all time ranges (N**2) and get an acceptable result.</p>
2
2009-09-19T03:34:42Z
[ "python", "datetime", "emacs", "overlap", "org-mode" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
1,447,562
<p>You can do what you need to do, but it isn't documented:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.encoder.FLOAT_REPR = lambda f: ("%.2f" % f) &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre>
7
2009-09-19T02:40:29Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
1,447,581
<p>Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library <code>json</code> package). E.g., this code:</p> <pre><code>import json from json import encoder encoder.FLOAT_REPR = lambda o: format(o, '.2f') print json.dumps(23.67) print json.dumps([23.67, 23.97, 23.87]) </code></pre> <p>emits:</p> <pre><code>23.67 [23.67, 23.97, 23.87] </code></pre> <p>as you desire. Obviously, there should be an architected way to override <code>FLOAT_REPR</code> so that EVERY representation of a float is under your control if you wish it to be; but unfortunately that's not how the <code>json</code> package was designed:-(.</p>
52
2009-09-19T02:48:41Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
1,645,929
<p>If you're stuck with Python 2.5 or earlier versions: The monkey-patch trick does not seem to work with the original simplejson module if the C speedups are installed:</p> <pre><code>$ python Python 2.5.4 (r254:67916, Jan 20 2009, 11:06:13) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import simplejson &gt;&gt;&gt; simplejson.__version__ '2.0.9' &gt;&gt;&gt; simplejson._speedups &lt;module 'simplejson._speedups' from '/home/carlos/.python-eggs/simplejson-2.0.9-py2.5-linux-i686.egg-tmp/simplejson/_speedups.so'&gt; &gt;&gt;&gt; simplejson.encoder.FLOAT_REPR = lambda f: ("%.2f" % f) &gt;&gt;&gt; simplejson.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' &gt;&gt;&gt; simplejson.encoder.c_make_encoder = None &gt;&gt;&gt; simplejson.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' &gt;&gt;&gt; </code></pre>
6
2009-10-29T19:15:58Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
1,733,105
<pre><code>import simplejson class PrettyFloat(float): def __repr__(self): return '%.15g' % self def pretty_floats(obj): if isinstance(obj, float): return PrettyFloat(obj) elif isinstance(obj, dict): return dict((k, pretty_floats(v)) for k, v in obj.items()) elif isinstance(obj, (list, tuple)): return map(pretty_floats, obj) return obj print simplejson.dumps(pretty_floats([23.67, 23.97, 23.87])) </code></pre> <p>emits</p> <pre><code>[23.67, 23.97, 23.87] </code></pre> <p>No monkeypatching necessary.</p>
37
2009-11-14T03:16:28Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
5,574,182
<p>If you're using Python 2.7, a simple solution is to simply round your floats explicitly to the desired precision.</p> <pre><code>&gt;&gt;&gt; sys.version '2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]' &gt;&gt;&gt; json.dumps(1.0/3.0) '0.3333333333333333' &gt;&gt;&gt; json.dumps(round(1.0/3.0, 2)) '0.33' </code></pre> <p>This works because Python 2.7 made <a href="http://docs.python.org/dev/whatsnew/2.7.html">float rounding more consistent</a>. Unfortunately this does not work in Python 2.6: </p> <pre><code>&gt;&gt;&gt; sys.version '2.6.6 (r266:84292, Dec 27 2010, 00:02:40) \n[GCC 4.4.5]' &gt;&gt;&gt; json.dumps(round(1.0/3.0, 2)) '0.33000000000000002' </code></pre> <p>The solutions mentioned above are workarounds for 2.6, but none are entirely adequate. Monkey patching json.encoder.FLOAT_REPR does not work if your Python runtime uses a C version of the JSON module. The PrettyFloat class in Tom Wuttke's answer works, but only if %g encoding works globally for your application. The %.15g is a bit magic, it works because float precision is 17 significant digits and %g does not print trailing zeroes.</p> <p>I spent some time trying to make a PrettyFloat that allowed customization of precision for each number. Ie, a syntax like</p> <pre><code>&gt;&gt;&gt; json.dumps(PrettyFloat(1.0 / 3.0, 4)) '0.3333' </code></pre> <p>It's not easy to get this right. Inheriting from float is awkward. Inheriting from Object and using a JSONEncoder subclass with its own default() method should work, except the json module seems to assume all custom types should be serialized as strings. Ie: you end up with the Javascript string "0.33" in the output, not the number 0.33. There may be a way yet to make this work, but it's harder than it looks.</p>
19
2011-04-06T23:29:36Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
6,245,594
<p>If you need to do this in python 2.7 without overriding the global json.encoder.FLOAT_REPR, here's one way.</p> <pre><code>import json import math class MyEncoder(json.JSONEncoder): "JSON encoder that renders floats to two decimal places" FLOAT_FRMT = '{0:.2f}' def floatstr(self, obj): return self.FLOAT_FRMT.format(obj) def _iterencode(self, obj, markers=None): # stl JSON lame override #1 new_obj = obj if isinstance(obj, float): if not math.isnan(obj) and not math.isinf(obj): new_obj = self.floatstr(obj) return super(MyEncoder, self)._iterencode(new_obj, markers=markers) def _iterencode_dict(self, dct, markers=None): # stl JSON lame override #2 new_dct = {} for key, value in dct.iteritems(): if isinstance(key, float): if not math.isnan(key) and not math.isinf(key): key = self.floatstr(key) new_dct[key] = value return super(MyEncoder, self)._iterencode_dict(new_dct, markers=markers) </code></pre> <p>Then, in python 2.7:</p> <pre><code>&gt;&gt;&gt; from tmp import MyEncoder &gt;&gt;&gt; enc = MyEncoder() &gt;&gt;&gt; enc.encode([23.67, 23.98, 23.87]) '[23.67, 23.98, 23.87]' </code></pre> <p>In python 2.6, it doesn't quite work as Matthew Schinckel points out below:</p> <pre><code>&gt;&gt;&gt; import MyEncoder &gt;&gt;&gt; enc = MyEncoder() &gt;&gt;&gt; enc.encode([23.67, 23.97, 23.87]) '["23.67", "23.97", "23.87"]' </code></pre>
0
2011-06-05T20:19:17Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
6,769,777
<p>Alex Martelli's solution will work for single threaded apps, but may not work for multi-threaded apps that need to control the number of decimal places per thread. Here is a solution that should work in multi threaded apps:</p> <pre><code>import threading from json import encoder def FLOAT_REPR(f): """ Serialize a float to a string, with a given number of digits """ decimal_places = getattr(encoder.thread_local, 'decimal_places', 0) format_str = '%%.%df' % decimal_places return format_str % f encoder.thread_local = threading.local() encoder.FLOAT_REPR = FLOAT_REPR #As an example, call like this: import json encoder.thread_local.decimal_places = 1 json.dumps([1.56, 1.54]) #Should result in '[1.6, 1.5]' </code></pre> <p>You can merely set encoder.thread_local.decimal_places to the number of decimal places you want, and the next call to json.dumps() in that thread will use that number of decimal places</p>
2
2011-07-20T23:35:23Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
9,777,521
<p>Pros:</p> <ul> <li>Works with any JSON encoder, or even python's repr. </li> <li>Short(ish), seems to work.</li> </ul> <p>Cons:</p> <ul> <li>Ugly regexp hack, barely tested.</li> <li><p>Quadratic complexity.</p> <pre><code>def fix_floats(json, decimals=2, quote='"'): pattern = r'^((?:(?:"(?:\\.|[^\\"])*?")|[^"])*?)(-?\d+\.\d{'+str(decimals)+'}\d+)' pattern = re.sub('"', quote, pattern) fmt = "%%.%df" % decimals n = 1 while n: json, n = re.subn(pattern, lambda m: m.group(1)+(fmt % float(m.group(2)).rstrip('0')), json) return json </code></pre></li> </ul>
1
2012-03-19T20:34:01Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
23,390,008
<p>When importing the standard json module, it is enough to change the default encoder FLOAT_REPR. There isn't really the need to import or create Encoder instances.</p> <pre><code>import json json.encoder.FLOAT_REPR = lambda o: format(o, '.2f') json.dumps([23.67, 23.97, 23.87]) #returns '[23.67, 23.97, 23.87]' </code></pre> <p>Sometimes is also very useful to output as json the best representation python can guess with str. This will make sure signifficant digits are not ignored.</p> <pre><code>import json json.dumps([23.67, 23.9779, 23.87489]) # output is'[23.670000000000002, 23.977900000000002, 23.874890000000001]' json.encoder.FLOAT_REPR = str json.dumps([23.67, 23.9779, 23.87489]) # output is '[23.67, 23.9779, 23.87489]' </code></pre>
1
2014-04-30T13:51:32Z
[ "python", "json", "formatting", "floating-point" ]
Format floats with standard json module
1,447,287
<p>I am using the standard <a href="http://docs.python.org/library/json.html">json module</a> in python 2.6 to serialize a list of floats. However, I'm getting results like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I want the floats to be formated with only two decimal digits. The output should look like this:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.67, 23.97, 23.87]' </code></pre> <p>I have tried defining my own JSON Encoder class:</p> <pre><code>class MyEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, float): return format(obj, '.2f') return json.JSONEncoder.encode(self, obj) </code></pre> <p>This works for a sole float object:</p> <pre><code>&gt;&gt;&gt; json.dumps(23.67, cls=MyEncoder) '23.67' </code></pre> <p>But fails for nested objects:</p> <pre><code>&gt;&gt;&gt; json.dumps([23.67, 23.97, 23.87]) '[23.670000000000002, 23.969999999999999, 23.870000000000001]' </code></pre> <p>I don't want to have external dependencies, so I prefer to stick with the standard json module.</p> <p>How can I achieve this?</p>
53
2009-09-19T00:08:37Z
29,066,406
<p>Really unfortunate that <code>dumps</code> doesn't allow you to do anything to floats. However <code>loads</code> does. So if you don't mind the extra CPU load, you could throw it through the encoder/decoder/encoder and get the right result:</p> <pre><code>&gt;&gt;&gt; json.dumps(json.loads(json.dumps([.333333333333, .432432]), parse_float=lambda x: round(float(x), 3))) '[0.333, 0.432]' </code></pre>
0
2015-03-15T21:30:41Z
[ "python", "json", "formatting", "floating-point" ]
How to send a file via HTTP, the good way, using Python?
1,447,353
<p>If a would-be-HTTP-server written in Python2.6 has local access to a file, what would be the most correct way for that server to return the file to a client, on request?</p> <p>Let's say this is the current situation:</p> <pre><code>header('Content-Type', file.mimetype) header('Content-Length', file.size) # file size in bytes header('Content-MD5', file.hash) # an md5 hash of the entire file return open(file.path).read() </code></pre> <p>All the files are .zip or .rar archives no bigger than a couple of megabytes.</p> <p>With the current situation, browsers handle the incoming download weirdly. No browser knows the file's name, for example, so they use a random or default one. (Firefox even saved the file with a .part extension, even though it was complete and completely usable.)</p> <p>What would be the best way to fix this and other errors I may not even be aware of, yet?</p> <p>What headers am I not sending?</p> <p>Thanks!</p>
5
2009-09-19T00:39:51Z
1,447,388
<p>If you don't have to return the response body (that is, if you are given a stream for the response body by your framework) you can avoid holding the file in memory with something like this:</p> <pre><code>fp = file(path_to_the_file, 'rb') while True: bytes = fp.read(8192) if bytes: response.write(bytes) else: return </code></pre> <p>What web framework are you using?</p>
1
2009-09-19T01:01:05Z
[ "python", "http", "http-headers" ]
How to send a file via HTTP, the good way, using Python?
1,447,353
<p>If a would-be-HTTP-server written in Python2.6 has local access to a file, what would be the most correct way for that server to return the file to a client, on request?</p> <p>Let's say this is the current situation:</p> <pre><code>header('Content-Type', file.mimetype) header('Content-Length', file.size) # file size in bytes header('Content-MD5', file.hash) # an md5 hash of the entire file return open(file.path).read() </code></pre> <p>All the files are .zip or .rar archives no bigger than a couple of megabytes.</p> <p>With the current situation, browsers handle the incoming download weirdly. No browser knows the file's name, for example, so they use a random or default one. (Firefox even saved the file with a .part extension, even though it was complete and completely usable.)</p> <p>What would be the best way to fix this and other errors I may not even be aware of, yet?</p> <p>What headers am I not sending?</p> <p>Thanks!</p>
5
2009-09-19T00:39:51Z
1,447,400
<p>This is how I send ZIP file,</p> <pre><code> req.send_response(200) req.send_header('Content-Type', 'application/zip') req.send_header('Content-Disposition', 'attachment;' 'filename=%s' % filename) </code></pre> <p>Most browsers handle it correctly.</p>
6
2009-09-19T01:04:49Z
[ "python", "http", "http-headers" ]
Installed Python to portable python
1,447,422
<p>I have installed python from .msi installer in windows and installed a lot of other modules. i would like to have all these available on a portable thumbdrive, but i don't want to redownload all the extramodules. Is there a way i can convert my C:\python26* to a portable python installation?</p>
1
2009-09-19T01:19:00Z
1,447,430
<p>Python is pretty smart about knowing where it is run from. What happens if you just copy the whole directory tree to the thumb drive?</p>
1
2009-09-19T01:21:30Z
[ "python" ]
How do I see the results of my class on a file?
1,447,487
<p>I found this class to take a space delimited file and if there are multiple spaces, they will be treated as a single separator. How do I see the effects of this on a file?</p> <pre><code>class FH: def __init__(self, fh): self.fh = fh def close(self): self.fh.close() def seek(self, arg): self.fh.seek(arg) def fix(self, s): return ' '.join(s.split()) def next(self): return self.fix(self.fh.next()) def __iter__(self): for line in self.fh: yield self.fix(line) </code></pre> <p>so how do I see this work on a file? I've created a file with multiple spaces to see it in action.</p> <p>I've done this:</p> <pre> In [31]: FH('classfhtry.csv') Out[31]: In [32]: r = FH('classfhtry.csv') In [33]: r Out[33]: In [34]: print r -------> print(r) In [35]: f = open(r) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in () ----> 1 2 3 4 5 TypeError: coercing to Unicode: need string or buffer, instance found </pre> <p>I want to see my class in action! Thanks for any 2cents!</p>
0
2009-09-19T01:52:10Z
1,447,512
<p>Looks like this class takes a file (not a file name) in the initializer. Try:</p> <pre><code>r = FH(file('classfhtry.csv', 'r')) for line in r: print line </code></pre>
5
2009-09-19T02:07:08Z
[ "python", "class" ]
How do I see the results of my class on a file?
1,447,487
<p>I found this class to take a space delimited file and if there are multiple spaces, they will be treated as a single separator. How do I see the effects of this on a file?</p> <pre><code>class FH: def __init__(self, fh): self.fh = fh def close(self): self.fh.close() def seek(self, arg): self.fh.seek(arg) def fix(self, s): return ' '.join(s.split()) def next(self): return self.fix(self.fh.next()) def __iter__(self): for line in self.fh: yield self.fix(line) </code></pre> <p>so how do I see this work on a file? I've created a file with multiple spaces to see it in action.</p> <p>I've done this:</p> <pre> In [31]: FH('classfhtry.csv') Out[31]: In [32]: r = FH('classfhtry.csv') In [33]: r Out[33]: In [34]: print r -------> print(r) In [35]: f = open(r) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in () ----> 1 2 3 4 5 TypeError: coercing to Unicode: need string or buffer, instance found </pre> <p>I want to see my class in action! Thanks for any 2cents!</p>
0
2009-09-19T01:52:10Z
1,447,533
<p>dcrosta is correct. The class expects a space delimited contents in the file. Have a file like:</p> <p>somefile.txt</p> <pre><code>one two three four five six </code></pre> <p>And follow the method as suggested above. The class is an iterator (it yields the lines from the file obj). So, the way to access to the file is the iterate through the contents.</p>
0
2009-09-19T02:19:20Z
[ "python", "class" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
1,447,591
<p>Problem is, as explained e.g. <a href="http://en.wikipedia.org/wiki/Symbolic%5Flink#Microsoft%5FWindows">here</a>, that Windows' own support for the functionality of symbolic links varies across Windows releases, so that e.g. in Vista (with lots of work) you can get more functionality than in XP or 2000 (nothing AFAIK on other win32 versions). Or you could have shortcuts instead, which of course have their own set of limitations and aren't "really" equivalent to Unix symbolic links. So, you have to specify exactly what functionalities you require, how much of those you are willing to sacrifice on the altar of cross-win32 operation, etc -- THEN, we can work out how to implement the compromise you've chosen in terms of <code>ctypes</code> or <code>win32all</code> calls... that's the least of it, in a sense.</p>
8
2009-09-19T02:54:33Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
1,447,651
<p>NTFS file system has junction points, i think you may use them instead</p> <p>copied from my answer to <a href="http://stackoverflow.com/questions/1143260/create-ntfs-junction-point-in-python">Create NTFS junction point in Python</a></p> <p>you can use python win32 API modules e.g.</p> <pre><code>import win32file win32file.CreateSymbolicLink(fileSrc, fileTarget, 1) </code></pre> <p>see <a href="http://docs.activestate.com/activepython/2.7/pywin32/win32file__CreateSymbolicLink_meth.html">http://docs.activestate.com/activepython/2.7/pywin32/win32file__CreateSymbolicLink_meth.html</a> for more details</p> <p>if you do not want to rely on that too, you can always use ctypes and directly call <code>CreateSymbolicLink</code> win32 API, which is anyway a simple call</p> <p>here is example call using ctypes</p> <pre><code>import ctypes kdll = ctypes.windll.LoadLibrary("kernel32.dll") kdll.CreateSymbolicLinkA("d:\\test.txt", "d:\\test_link.txt", 0) </code></pre> <p>MSDN (<a href="http://msdn.microsoft.com/en-us/library/aa363866(VS.85).aspx">http://msdn.microsoft.com/en-us/library/aa363866(VS.85).aspx</a>) says Minimum supported client Windows Vista</p> <p><strong>In addition</strong>: This also works with directories (indicate that with the third argument). With unicode support it looks like this:</p> <pre><code>kdll.CreateSymbolicLinkW(UR"D:\testdirLink", UR"D:\testdir", 1) </code></pre>
27
2009-09-19T03:37:05Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
4,388,195
<p>I put the following into Lib/site-packages/sitecustomize.py</p> <pre><code>import os __CSL = None def symlink(source, link_name): '''symlink(source, link_name) Creates a symbolic link pointing to source named link_name''' global __CSL if __CSL is None: import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte __CSL = csl flags = 0 if source is not None and os.path.isdir(source): flags = 1 if __CSL(link_name, source, flags) == 0: raise ctypes.WinError() os.symlink = symlink </code></pre>
4
2010-12-08T13:49:47Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
7,924,557
<p><a href="https://github.com/juntalis/ntfslink-python">python ntfslink extension</a></p> <p>Or if you want to use pywin32, you can use the previously stated method, and to read, use:</p> <pre><code>from win32file import * from winioctlcon import FSCTL_GET_REPARSE_POINT __all__ = ['islink', 'readlink'] # Win32file doesn't seem to have this attribute. FILE_ATTRIBUTE_REPARSE_POINT = 1024 # To make things easier. REPARSE_FOLDER = (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) # For the parse_reparse_buffer function SYMBOLIC_LINK = 'symbolic' MOUNTPOINT = 'mountpoint' GENERIC = 'generic' def islink(fpath): """ Windows islink implementation. """ if GetFileAttributes(fpath) &amp; REPARSE_FOLDER == REPARSE_FOLDER: return True return False def parse_reparse_buffer(original, reparse_type=SYMBOLIC_LINK): """ Implementing the below in Python: typedef struct _REPARSE_DATA_BUFFER { ULONG ReparseTag; USHORT ReparseDataLength; USHORT Reserved; union { struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; ULONG Flags; WCHAR PathBuffer[1]; } SymbolicLinkReparseBuffer; struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; WCHAR PathBuffer[1]; } MountPointReparseBuffer; struct { UCHAR DataBuffer[1]; } GenericReparseBuffer; } DUMMYUNIONNAME; } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER; """ # Size of our data types SZULONG = 4 # sizeof(ULONG) SZUSHORT = 2 # sizeof(USHORT) # Our structure. # Probably a better way to iterate a dictionary in a particular order, # but I was in a hurry, unfortunately, so I used pkeys. buffer = { 'tag' : SZULONG, 'data_length' : SZUSHORT, 'reserved' : SZUSHORT, SYMBOLIC_LINK : { 'substitute_name_offset' : SZUSHORT, 'substitute_name_length' : SZUSHORT, 'print_name_offset' : SZUSHORT, 'print_name_length' : SZUSHORT, 'flags' : SZULONG, 'buffer' : u'', 'pkeys' : [ 'substitute_name_offset', 'substitute_name_length', 'print_name_offset', 'print_name_length', 'flags', ] }, MOUNTPOINT : { 'substitute_name_offset' : SZUSHORT, 'substitute_name_length' : SZUSHORT, 'print_name_offset' : SZUSHORT, 'print_name_length' : SZUSHORT, 'buffer' : u'', 'pkeys' : [ 'substitute_name_offset', 'substitute_name_length', 'print_name_offset', 'print_name_length', ] }, GENERIC : { 'pkeys' : [], 'buffer': '' } } # Header stuff buffer['tag'] = original[:SZULONG] buffer['data_length'] = original[SZULONG:SZUSHORT] buffer['reserved'] = original[SZULONG+SZUSHORT:SZUSHORT] original = original[8:] # Parsing k = reparse_type for c in buffer[k]['pkeys']: if type(buffer[k][c]) == int: sz = buffer[k][c] bytes = original[:sz] buffer[k][c] = 0 for b in bytes: n = ord(b) if n: buffer[k][c] += n original = original[sz:] # Using the offset and length's grabbed, we'll set the buffer. buffer[k]['buffer'] = original return buffer def readlink(fpath): """ Windows readlink implementation. """ # This wouldn't return true if the file didn't exist, as far as I know. if not islink(fpath): return None # Open the file correctly depending on the string type. handle = CreateFileW(fpath, GENERIC_READ, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, 0) \ if type(fpath) == unicode else \ CreateFile(fpath, GENERIC_READ, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, 0) # MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 = (16*1024) buffer = DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, None, 16*1024) # Above will return an ugly string (byte array), so we'll need to parse it. # But first, we'll close the handle to our file so we're not locking it anymore. CloseHandle(handle) # Minimum possible length (assuming that the length of the target is bigger than 0) if len(buffer) &lt; 9: return None # Parse and return our result. result = parse_reparse_buffer(buffer) offset = result[SYMBOLIC_LINK]['substitute_name_offset'] ending = offset + result[SYMBOLIC_LINK]['substitute_name_length'] rpath = result[SYMBOLIC_LINK]['buffer'][offset:ending].replace('\x00','') if len(rpath) &gt; 4 and rpath[0:4] == '\\??\\': rpath = rpath[4:] return rpath def realpath(fpath): from os import path while islink(fpath): rpath = readlink(fpath) if not path.isabs(rpath): rpath = path.abspath(path.join(path.dirname(fpath), rpath)) fpath = rpath return fpath def example(): from os import system, unlink system('cmd.exe /c echo Hello World &gt; test.txt') system('mklink test-link.txt test.txt') print 'IsLink: %s' % islink('test-link.txt') print 'ReadLink: %s' % readlink('test-link.txt') print 'RealPath: %s' % realpath('test-link.txt') unlink('test-link.txt') unlink('test.txt') if __name__=='__main__': example() </code></pre> <p>Adjust the attributes in the CreateFile to your needs, but for a normal situation, it should work. Feel free to improve on it.</p> <p>It should also work for folder junctions if you use MOUNTPOINT instead of SYMBOLIC_LINK.</p> <p>You may way to check that</p> <pre><code>sys.getwindowsversion()[0] &gt;= 6 </code></pre> <p>if you put this into something you're releasing, since this form of symbolic link is only supported on Vista+.</p>
9
2011-10-28T02:35:43Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
10,392,885
<p>Juntalis's code does not handle Unicode so I modified it to use ctypes and also simplified it using struct. I've also consulted the code from <a href="http://stackoverflow.com/questions/8744246/using-a-struct-as-a-function-argument-with-the-python-ctypes-module">Using a struct as a function argument with the python ctypes module</a></p> <pre><code>import os, ctypes, struct from ctypes import windll, wintypes FSCTL_GET_REPARSE_POINT = 0x900a8 FILE_ATTRIBUTE_READONLY = 0x0001 FILE_ATTRIBUTE_HIDDEN = 0x0002 FILE_ATTRIBUTE_DIRECTORY = 0x0010 FILE_ATTRIBUTE_NORMAL = 0x0080 FILE_ATTRIBUTE_REPARSE_POINT = 0x0400 GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 OPEN_EXISTING = 3 FILE_READ_ATTRIBUTES = 0x80 FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF FILE_FLAG_OPEN_REPARSE_POINT = 2097152 FILE_FLAG_BACKUP_SEMANTICS = 33554432 # FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTI FILE_FLAG_REPARSE_BACKUP = 35651584 GetFileAttributes = windll.kernel32.GetFileAttributesW _CreateFileW = windll.kernel32.CreateFileW _DevIoCtl = windll.kernel32.DeviceIoControl _DevIoCtl.argtypes = [ wintypes.HANDLE, #HANDLE hDevice wintypes.DWORD, #DWORD dwIoControlCode wintypes.LPVOID, #LPVOID lpInBuffer wintypes.DWORD, #DWORD nInBufferSize wintypes.LPVOID, #LPVOID lpOutBuffer wintypes.DWORD, #DWORD nOutBufferSize ctypes.POINTER(wintypes.DWORD), #LPDWORD lpBytesReturned wintypes.LPVOID] #LPOVERLAPPED lpOverlapped _DevIoCtl.restype = wintypes.BOOL def islink(path): assert os.path.isdir(path), path if GetFileAttributes(path) &amp; FILE_ATTRIBUTE_REPARSE_POINT: return True else: return False def DeviceIoControl(hDevice, ioControlCode, input, output): # DeviceIoControl Function # http://msdn.microsoft.com/en-us/library/aa363216(v=vs.85).aspx if input: input_size = len(input) else: input_size = 0 if isinstance(output, int): output = ctypes.create_string_buffer(output) output_size = len(output) assert isinstance(output, ctypes.Array) bytesReturned = wintypes.DWORD() status = _DevIoCtl(hDevice, ioControlCode, input, input_size, output, output_size, bytesReturned, None) print "status(%d)" % status if status != 0: return output[:bytesReturned.value] else: return None def CreateFile(path, access, sharemode, creation, flags): return _CreateFileW(path, access, sharemode, None, creation, flags, None) SymbolicLinkReparseFormat = "LHHHHHHL" SymbolicLinkReparseSize = struct.calcsize(SymbolicLinkReparseFormat); def readlink(path): """ Windows readlink implementation. """ # This wouldn't return true if the file didn't exist, as far as I know. assert islink(path) assert type(path) == unicode # Open the file correctly depending on the string type. hfile = CreateFile(path, GENERIC_READ, 0, OPEN_EXISTING, FILE_FLAG_REPARSE_BACKUP) # MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 = (16*1024) buffer = DeviceIoControl(hfile, FSCTL_GET_REPARSE_POINT, None, 16384) CloseHandle(hfile) # Minimum possible length (assuming length of the target is bigger than 0) if not buffer or len(buffer) &lt; 9: return None # Parse and return our result. # typedef struct _REPARSE_DATA_BUFFER { # ULONG ReparseTag; # USHORT ReparseDataLength; # USHORT Reserved; # union { # struct { # USHORT SubstituteNameOffset; # USHORT SubstituteNameLength; # USHORT PrintNameOffset; # USHORT PrintNameLength; # ULONG Flags; # WCHAR PathBuffer[1]; # } SymbolicLinkReparseBuffer; # struct { # USHORT SubstituteNameOffset; # USHORT SubstituteNameLength; # USHORT PrintNameOffset; # USHORT PrintNameLength; # WCHAR PathBuffer[1]; # } MountPointReparseBuffer; # struct { # UCHAR DataBuffer[1]; # } GenericReparseBuffer; # } DUMMYUNIONNAME; # } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER; # Only handle SymbolicLinkReparseBuffer (tag, dataLength, reserver, SubstituteNameOffset, SubstituteNameLength, PrintNameOffset, PrintNameLength, Flags) = struct.unpack(SymbolicLinkReparseFormat, buffer[:SymbolicLinkReparseSize]) print tag, dataLength, reserver, SubstituteNameOffset, SubstituteNameLength start = SubstituteNameOffset + SymbolicLinkReparseSize actualPath = buffer[start : start + SubstituteNameLength].decode("utf-16") # This utf-16 string is null terminated index = actualPath.find(u"\0") assert index &gt; 0 if index &gt; 0: actualPath = actualPath[:index] if actualPath.startswith(u"?\\"): return actualPath[2:] else: return actualPath </code></pre>
1
2012-05-01T02:34:13Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
20,511,634
<p>os.symlink works on Python 3.3 using Windows 8.1 with an NTFS filesystem.</p>
2
2013-12-11T05:59:38Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
21,636,530
<p>here is the link containing all methods of kernel32.dll</p> <p><a href="http://www.geoffchappell.com/studies/windows/win32/kernel32/api/" rel="nofollow">http://www.geoffchappell.com/studies/windows/win32/kernel32/api/</a></p> <p>I used CreateHardLinkA on Windows xp sp3, it worked!</p> <p>import ctypes if os.path.exists(link_file): os.remove(link_file)</p> <pre><code>dll = ctypes.windll.LoadLibrary("kernel32.dll") dll.CreateHardLinkA(link_file, _log_filename, 0) </code></pre>
-1
2014-02-07T19:47:56Z
[ "python", "winapi", "symlink", "pywin32" ]
Symlinks on windows?
1,447,575
<p>Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform.</p>
25
2009-09-19T02:44:58Z
22,225,651
<p>Using mklink command in subprocess create link.</p> <pre><code>from subprocess import call call(['mklink', 'LINK', 'TARGET'], shell=True) </code></pre>
1
2014-03-06T13:13:59Z
[ "python", "winapi", "symlink", "pywin32" ]
Error trying to pass (large) image over socket in python
1,447,684
<p>I am trying to pass an image over python socket for smaller images it works fine but for larger images it gives error as</p> <p>socket.error: [Errno 10040] A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself</p> <p>I am using </p> <pre><code>socket.socket(socket.AF_INET, socket.SOCK_DGRAM) </code></pre> <p>Thanks for any clue . </p> <p>I tried using SOCK_STREAM, it does not work .. It just says me starting ... and hangs out . with no output .. Its not coming out of send function</p> <pre><code>import thread import socket import ImageGrab class p2p: def __init__(self): socket.setdefaulttimeout(50) #send port self.send_port = 3000 #receive port self.recv_port=2000 #OUR IP HERE self.peerid = '127.0.0.1:' #DESTINATION self.recv_peers = '127.0.0.1' #declaring sender socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM ) self.socket.bind(('127.0.0.1', self.send_port)) self.socket.settimeout(50) #receiver socket self.serverSocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM ) self.serverSocket.bind(('127.0.0.1', self.recv_port)) self.serverSocket.settimeout(50) #starting thread for reception thread.start_new_thread(self.receiveData, ()) #grabbing screenshot image = ImageGrab.grab() image.save("c:\\test.jpg") f = open("c:\\ test.jpg", "rb") data = f.read() #sending self.sendData(data) print 'sent...' f.close() while 1: pass def receiveData(self): f = open("c:\\received.png","wb") while 1: data,address = self.serverSocket.recvfrom(1024) if not data: break f.write(data) try: f.close() except: print 'could not save' print "received" def sendData(self,data): self.socket.sendto(data, (self.recv_peers,self.recv_port)) if __name__=='__main__': print 'Started......' p2p() </code></pre>
1
2009-09-19T03:52:22Z
1,447,690
<p><a href="http://support.ipswitch.com/kb/WSK-19980714-EM13.htm" rel="nofollow">The message you are sending is being truncated</a>.</p> <p>Since you haven't shown the actual code that <code>send</code>s, I'm guessing you are trying to write the entire image to the socket. You'll have to break the image into several, smaller chunks.</p>
2
2009-09-19T03:55:41Z
[ "python", "sockets" ]
Error trying to pass (large) image over socket in python
1,447,684
<p>I am trying to pass an image over python socket for smaller images it works fine but for larger images it gives error as</p> <p>socket.error: [Errno 10040] A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself</p> <p>I am using </p> <pre><code>socket.socket(socket.AF_INET, socket.SOCK_DGRAM) </code></pre> <p>Thanks for any clue . </p> <p>I tried using SOCK_STREAM, it does not work .. It just says me starting ... and hangs out . with no output .. Its not coming out of send function</p> <pre><code>import thread import socket import ImageGrab class p2p: def __init__(self): socket.setdefaulttimeout(50) #send port self.send_port = 3000 #receive port self.recv_port=2000 #OUR IP HERE self.peerid = '127.0.0.1:' #DESTINATION self.recv_peers = '127.0.0.1' #declaring sender socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM ) self.socket.bind(('127.0.0.1', self.send_port)) self.socket.settimeout(50) #receiver socket self.serverSocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM ) self.serverSocket.bind(('127.0.0.1', self.recv_port)) self.serverSocket.settimeout(50) #starting thread for reception thread.start_new_thread(self.receiveData, ()) #grabbing screenshot image = ImageGrab.grab() image.save("c:\\test.jpg") f = open("c:\\ test.jpg", "rb") data = f.read() #sending self.sendData(data) print 'sent...' f.close() while 1: pass def receiveData(self): f = open("c:\\received.png","wb") while 1: data,address = self.serverSocket.recvfrom(1024) if not data: break f.write(data) try: f.close() except: print 'could not save' print "received" def sendData(self,data): self.socket.sendto(data, (self.recv_peers,self.recv_port)) if __name__=='__main__': print 'Started......' p2p() </code></pre>
1
2009-09-19T03:52:22Z
1,447,700
<p>Your image is too big to be sent in one UDP packet. You need to split the image data into several packets that are sent individually.</p> <p>If you don't have a special reason to use UDP you could also use TCP by specifying <code>socket.SOCK_STREAM</code> instead of <code>socket.SOCK_DGRAM</code>. There you don't have to worry about packet sizes and ordering.</p>
5
2009-09-19T04:02:13Z
[ "python", "sockets" ]
Django ORM, filtering objects by type with model inheritence
1,447,742
<p>So I have two models...</p> <p>Parent and Child.</p> <p>Child extends Parent.</p> <p>When I do</p> <p>Parent.objects.all(), I get both the Parents and the Children.</p> <p>I only want Parents</p> <p>Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?</p>
1
2009-09-19T04:30:04Z
1,447,755
<p>The <code>filter</code> method is essentially about building the WHERE clause in the SQL query, and that's a realy awkward place to be quibbling about exact types. What about, instead...:</p> <pre><code>(p for Parent.objects.all() if type(p) is Parent) </code></pre> <p>this is an iterable (use <code>[ ]</code> on the outside instead of <code>( )</code> if you want a list instead) for all objects that are <em>exactly</em> of type Parent - no subclasses allowed.</p>
2
2009-09-19T04:38:21Z
[ "python", "django", "django-models" ]
Django ORM, filtering objects by type with model inheritence
1,447,742
<p>So I have two models...</p> <p>Parent and Child.</p> <p>Child extends Parent.</p> <p>When I do</p> <p>Parent.objects.all(), I get both the Parents and the Children.</p> <p>I only want Parents</p> <p>Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?</p>
1
2009-09-19T04:30:04Z
1,448,340
<p>Are you sure that inheritance is the right solution here? What about this?</p> <pre><code>class MyModel(models.Model): foo = models.IntegerField() parent = models.ForeignKey("self", null=True) </code></pre> <p>Then you can query for all objects that are parents like this:</p> <pre><code>parents = MyModel.objects.filter(parent__isnull=True) children = MyModel.objects.filter(parent__isnull=False) </code></pre> <p>@Alex: filtering according to type won't work. Django's inheritance model isn't really that rich. E.g. with these models:</p> <pre><code>class Parent(models.Model): foo = models.CharField(max_length=5) class Child(Parent): bar = models.CharField(max_length=5) </code></pre> <p>you get this behavior: </p> <pre><code>In [1]: from myexample.models import Parent, Child In [2]: p = Parent(foo='x') In [3]: p.save() In [4]: p2 = Parent(foo='y') In [5]: p2.save() In [6]: c1 = Child(bar='1', foo='a') In [7]: c1.save() In [8]: c2 = Child(bar='2', foo='b') In [9]: c2.save() In [10]: len(Parent.objects.all()) Out[10]: 4 In [11]: len([p for p in Parent.objects.all() if type(p) is Parent]) Out[11]: 4 In [12]: len(Child.objects.all()) Out[12]: 2 </code></pre>
2
2009-09-19T11:08:15Z
[ "python", "django", "django-models" ]
Django ORM, filtering objects by type with model inheritence
1,447,742
<p>So I have two models...</p> <p>Parent and Child.</p> <p>Child extends Parent.</p> <p>When I do</p> <p>Parent.objects.all(), I get both the Parents and the Children.</p> <p>I only want Parents</p> <p>Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?</p>
1
2009-09-19T04:30:04Z
1,450,247
<p>Maybe it's a good place to use an <strong>A</strong>bstract <strong>B</strong>ase <strong>C</strong>lass instead of using inheritance. The ABC hold all the fields that are common to your classes. So, in your case, you will have one ABC mostly defined has your current Parent Class and 2 classes that will inherit from the ABC, that correspond to your Parent and Child classes.</p> <pre><code>class ABC(models.Model): field1 = models.CharField(max_length=200) field2 = models.CharField(max_length=100) .... class Meta: abstract = True class Parent(ABC): .... class Child(ABC): parent = models.ForeignKey(Parent) </code></pre> <p>Check here for more info : <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id5" rel="nofollow">Model inheritance and Abstract base classes</a></p>
3
2009-09-20T03:43:13Z
[ "python", "django", "django-models" ]
Django ORM, filtering objects by type with model inheritence
1,447,742
<p>So I have two models...</p> <p>Parent and Child.</p> <p>Child extends Parent.</p> <p>When I do</p> <p>Parent.objects.all(), I get both the Parents and the Children.</p> <p>I only want Parents</p> <p>Is there a Parent.objects.filter() argument I can use to only get the Parent objects instead of the objects that extend parent?</p>
1
2009-09-19T04:30:04Z
3,670,924
<p>I've found a better way to solve this, using the django ORM and without the need for any changes to your models (such as an ABC):</p> <blockquote> <pre><code>class Parent(models.Model): field1 = models.IntegerField() field2 = models.IntegerField() class Child(Parent): field3 = models.IntegerField() #Return all Parent objects that aren't also Child objects: Parent.objects.filter(child=None) </code></pre> </blockquote> <p>This will result in the following query(conceptual, actual query may vary):</p> <blockquote> <p>SELECT "ap_parent"."field1","ap_parent"."field2" FROM "ap_parent" INNER JOIN "ap_child" ON ("parent"."parent_ptr_id" = "ap_child"."parent_ptr_id") WHERE "ap_child"."parent_ptr_id" IS NULL</p> </blockquote>
12
2010-09-08T18:43:48Z
[ "python", "django", "django-models" ]
IDLE and Python have different path in Mac OS X
1,447,961
<p>I am running Mac OS X 10.5.8. I have installed Python 2.6 from the site. It's in my application directory. I have edited my .bash_profile to have:</p> <pre><code># Setting PATH for MacPython 2.6 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.6/bin:${PATH}" export PATH export PATH=/usr/local/mysql/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin export PYTHONPATH=/Users/blwatson/pythonpath:/Users/blwatson/pythonpath/django/bin:$PYTHONPATH </code></pre> <p>when I run python from the command prompt, I can get the following:</p> <pre><code>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import django &gt;&gt;&gt; django.VERSION (1, 0, 4, 'alpha', 0) </code></pre> <p>checking PATH</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/Users/blwatson/pythonpath', '/Users/blwatson/pythonpath/django/bin', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/wx-2.8-mac-unicode'] &gt;&gt;&gt; </code></pre> <p>When I am in IDLE, I get a different experience.</p> <pre><code>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 2.6.2 &gt;&gt;&gt; import django Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import django ImportError: No module named django &gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.path ['/Users/blwatson/Documents', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/wx-2.8-mac-unicode'] </code></pre> <p>I have no idea what's going on. I moved from one laptop to another and did the whole TimeCapsule thing, so I know that there's some conflict because of that. Where is IDLE getting the PATH from? Why can't I import Django?</p>
2
2009-09-19T06:34:45Z
1,448,009
<p>Seems to be a common problem:</p> <p><a href="http://www.google.com/search?q=python+idle+pythonpath" rel="nofollow">http://www.google.com/search?q=python+idle+pythonpath</a></p> <p>Unfortunately, no answers. The only suggestion seemed to be to edit the <code>idle</code> executable and adding a few <code>sys.path.insert(...)</code> lines.</p>
0
2009-09-19T07:09:35Z
[ "python", "django" ]
IDLE and Python have different path in Mac OS X
1,447,961
<p>I am running Mac OS X 10.5.8. I have installed Python 2.6 from the site. It's in my application directory. I have edited my .bash_profile to have:</p> <pre><code># Setting PATH for MacPython 2.6 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.6/bin:${PATH}" export PATH export PATH=/usr/local/mysql/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin export PYTHONPATH=/Users/blwatson/pythonpath:/Users/blwatson/pythonpath/django/bin:$PYTHONPATH </code></pre> <p>when I run python from the command prompt, I can get the following:</p> <pre><code>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import django &gt;&gt;&gt; django.VERSION (1, 0, 4, 'alpha', 0) </code></pre> <p>checking PATH</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/Users/blwatson/pythonpath', '/Users/blwatson/pythonpath/django/bin', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/wx-2.8-mac-unicode'] &gt;&gt;&gt; </code></pre> <p>When I am in IDLE, I get a different experience.</p> <pre><code>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 2.6.2 &gt;&gt;&gt; import django Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import django ImportError: No module named django &gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.path ['/Users/blwatson/Documents', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL', '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/wx-2.8-mac-unicode'] </code></pre> <p>I have no idea what's going on. I moved from one laptop to another and did the whole TimeCapsule thing, so I know that there's some conflict because of that. Where is IDLE getting the PATH from? Why can't I import Django?</p>
2
2009-09-19T06:34:45Z
1,448,173
<p>Like all OS X application bundles, if you launch <code>IDLE.app</code> by double-clicking, a shell is not involved and thus .<code>bash_profile</code> or other shell initialization files are not invoked. There is a way to set user session environment variables through the use of a special <a href="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html" rel="nofollow">property list file</a> (<code>~/.MacOSX/environment.plist</code>) but it really is a bit of a kludge and not recommended.</p> <p>Fortunately, there is a simpler solution: on OS X, it is also possible to invoke <code>IDLE</code> from a shell command line in a terminal window. In this way, it will inherit exported environment variables from that shell as you would expect. So something like:</p> <pre><code>$ export PYTHONPATH= ... $ /usr/local/bin/idle2.6 </code></pre> <p>There were various inconsistencies and problems with IDLE on OS X prior to 2.6.2 depending on how it was invoked so I recommend using nothing older than the python.org 2.6.2 or 3.1 versions on OS X.</p> <p>EDIT: I see from the <code>open(1)</code> man page that, since 10.4, applications launched via <code>open</code> also inherit environment variables so that would work from the command line as well. If you want to avoid opening a terminal window, it is easy to create a simple launcher app using AppleScript or Automator (or even Python with py2app!). In this case, use the open command command so that the launcher app does not sit around. For example, in <a href="http://apple.com/automator" rel="nofollow">Automator</a>, choose the <code>Run Shell Script</code> action and add:</p> <pre><code>export PYTHONPATH= ... open -a "/Applications/Python 2.6/IDLE.app" </code></pre> <p>Save it as File Format <code>Application</code> (in 10.5) and you should have a clickable way to launch a tailored IDLE.</p>
2
2009-09-19T08:46:23Z
[ "python", "django" ]
Decorators should not have side effects?
1,447,996
<p>Editing because the initial code was confusing.</p> <p>I would assume these two things to be same,</p> <pre><code>#I would use either of these #Option 1 def bar(*args): pass foo = deco(bar) #Option2 @deco def foo(*args): pass </code></pre> <p>However if the decorators <code>deco</code> has side effects, this is not guaranteed. In partcicular, this was my ecpectation form a decorator(no side effect), and I came across one with side effct and was bitten by it,</p> <pre><code>#Option1 def bar(*args): pass foo = register.filter(bar) #Option 2 @register.filter def foo(val, arg): pass </code></pre> <p>So is my expectation wrong, or is django being inconsistent with the best practices?</p>
0
2009-09-19T07:01:06Z
1,448,006
<p>Actually, these both are exactly the same:</p> <pre><code>def foo(*args): pass foo = deco(foo) @deco def foo(*args): pass </code></pre> <p>If you want to decorate <code>bar</code> and call it <code>foo</code>, <code>foo = deco(bar)</code> is the right way. It says: "decorate this previously defined thing called <code>bar</code> and call it <code>foo</code>". The point of the decorator syntax is to state the wrapping function before the definition, not to rename it.</p> <p>Unless you need to use <code>bar</code> later, there is no reason to call the undecorated function with a different name. By doing this you lose precisely the ability to use the decorator syntax sugar.</p> <p><code>deco</code> doesn't need to be a function. It can be an object with a <code>__call__</code> method, which is useful precisely to encapsulate side effects. </p>
2
2009-09-19T07:07:57Z
[ "python", "django", "decorator" ]
Decorators should not have side effects?
1,447,996
<p>Editing because the initial code was confusing.</p> <p>I would assume these two things to be same,</p> <pre><code>#I would use either of these #Option 1 def bar(*args): pass foo = deco(bar) #Option2 @deco def foo(*args): pass </code></pre> <p>However if the decorators <code>deco</code> has side effects, this is not guaranteed. In partcicular, this was my ecpectation form a decorator(no side effect), and I came across one with side effct and was bitten by it,</p> <pre><code>#Option1 def bar(*args): pass foo = register.filter(bar) #Option 2 @register.filter def foo(val, arg): pass </code></pre> <p>So is my expectation wrong, or is django being inconsistent with the best practices?</p>
0
2009-09-19T07:01:06Z
1,448,797
<p>Your examples do not express the same things in every case! Why do you insist on using bar? </p> <p>Take your first example:</p> <pre><code>#Option 1 def bar(*args): pass foo = deco(bar) #Option2 @deco def foo(*args): pass </code></pre> <p>Option 1 does (literally)</p> <pre><code>foo = deco(bar) </code></pre> <p>but Option 2 is the equivalent of</p> <pre><code>foo = deco(foo) </code></pre> <p>Can't you see the difference there?</p> <p>So, in short, yes: your assumption and your expectations are wrong.</p> <p>If you need the undecorated version of your function, as well as the decorated one, just save it beforehand:</p> <pre><code>def foo(*args): pass bar = foo foo = deco(foo) </code></pre>
0
2009-09-19T15:43:04Z
[ "python", "django", "decorator" ]
How to integrate JQGrid with Django/Python
1,448,143
<p>Anybody out there who have tried to use <a href="http://www.trirand.com/blog/" rel="nofollow">JQGrid</a> a Jquery plugin with django? </p> <p>Please share your knowledge/code samples</p> <p>Gath</p>
4
2009-09-19T08:23:11Z
1,500,293
<p>I'm trying to use it for the first day today. Right now I have imported an existing jquery app into a django project/app and now trying to get jqgrid to work with it. The thing I'm running into is having the javascript file actually call the python script for the json call for jgrid.</p> <p>I have no idea if this is working or not...I watch the apache logs and I don't see the file being served. I can reach the python script fine in the browser directly.</p> <p>Right now I'm just trying to go around django and get it to work with straight html/python/javascript. In the example they just have the javascript file call a php file like this. </p> <p>url:'server.php?q=1', </p> <p>well mine is located at like <a href="http://localhost/pythonScripts/server.py" rel="nofollow">http://localhost/pythonScripts/server.py</a> with mod_python running. I would love to get this working, but it is going to take alot of trial and error. Hopefully I can eventually get it all the way to django.</p>
-2
2009-09-30T19:48:53Z
[ "jquery", "python", "django", "jqgrid" ]
How to integrate JQGrid with Django/Python
1,448,143
<p>Anybody out there who have tried to use <a href="http://www.trirand.com/blog/" rel="nofollow">JQGrid</a> a Jquery plugin with django? </p> <p>Please share your knowledge/code samples</p> <p>Gath</p>
4
2009-09-19T08:23:11Z
1,615,475
<p>I've find a project that has already implemented integration look at Google code <a href="http://code.google.com/p/django-jqgrid/" rel="nofollow">http://code.google.com/p/django-jqgrid/</a></p>
3
2009-10-23T19:34:14Z
[ "jquery", "python", "django", "jqgrid" ]
How to integrate JQGrid with Django/Python
1,448,143
<p>Anybody out there who have tried to use <a href="http://www.trirand.com/blog/" rel="nofollow">JQGrid</a> a Jquery plugin with django? </p> <p>Please share your knowledge/code samples</p> <p>Gath</p>
4
2009-09-19T08:23:11Z
4,235,226
<p>Is there any latest info on this? Looks like django-jqgrid not updated in a year</p>
1
2010-11-20T21:58:53Z
[ "jquery", "python", "django", "jqgrid" ]
How to integrate JQGrid with Django/Python
1,448,143
<p>Anybody out there who have tried to use <a href="http://www.trirand.com/blog/" rel="nofollow">JQGrid</a> a Jquery plugin with django? </p> <p>Please share your knowledge/code samples</p> <p>Gath</p>
4
2009-09-19T08:23:11Z
9,029,522
<p>take a look at <a href="http://readthedocs.org/docs/django-jquery-grid-admin/en/latest/" rel="nofollow">django-jquery-grid-admin</a></p>
0
2012-01-27T05:58:46Z
[ "jquery", "python", "django", "jqgrid" ]
Python SOCK_STREAM over internet
1,448,193
<p>I have a simple programs for socket client and server its not working over internet</p> <pre><code># Echo server program import socket import ImageGrab HOST = '' # Symbolic name meaning all available interfaces PORT = 3000 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr data = conn.recv(1024) print data conn.close() # Echo client program import socket import ImageGrab #destnation ip HOST = '127.0.0.1' # The remote host PORT = 3000 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello rushikesh') s.close() print 'Received'#, repr(data) </code></pre> <p>When we try to make it work over internet it is not able to connect. Program is shown as above only thing is destination ip is replaces by my friends ip. </p> <p>When working over localhost it works perfectly fine but not working over internet ...</p> <p>I have written program using <code>SOCK_DGRAM</code> it works over internet only for small chunks of data. I want to transmit image using it so I have written it using <code>SOCK_STREAM</code> for transmitting image which successfully worked on localhost and was not working over internet. So I did write simplest program but still showing same problem</p> <p>Can somebody please guid me through this...</p>
2
2009-09-19T08:55:44Z
1,448,227
<p>You've got the right approach, but you are probably running into networking or firewall problems. Depending on how your friend's networking is configured, he may be behind NAT or a firewall that prevents you from making a direct connection into his computer.</p> <p>To eliminate half the problem, you can use <code>telnet</code> as a client to make a simple connection to the server to see whether it is available:</p> <pre><code>telnet 127.0.0.1 3000 </code></pre> <p>If <code>telnet</code> connects successfully, then the networking works. If it fails, then there is something else wrong (and may give you information that might help discover what).</p>
4
2009-09-19T09:24:45Z
[ "python", "sockets" ]
What are the best benefits of using Pinax?
1,448,292
<p>I recently discovered <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> that appear to be an django stack with added most-used apps so easy and speed up development.</p> <p>I never used or heard of Pinax before and like to know if you have feedback about it. I love Django and would like to understand what are to parts of web dev Pinax helps with and using what tools. </p>
24
2009-09-19T10:28:01Z
1,448,640
<p>Pinax is a collection of Django-Apps that have already been glued together for you with some code and sample templates.</p> <p>It's not plug&amp;play, because Django is not a CMS and Apps are not plugins, but you can get your site going really fast. You just have to remove the stuff you don't need, add other Django Apps that you'd like to use from around the web and write the stuff that nobody has written before and that makes your site special.</p> <p>I worked on a site with Pinax and had to remove quite a lot, to make it more simple, but it was still totally worth it.</p> <p>It's a great example (probably the best) of how Django Apps are reusable and how to make them work together best.</p> <p>Concrete example, here you go: Pinax comes with all the "User" Part of an online community: login, registration, OpenID, E-Mail-Confirmation. That's an example of what you don't have to write.</p>
13
2009-09-19T14:25:29Z
[ "python", "django", "pinax" ]
What are the best benefits of using Pinax?
1,448,292
<p>I recently discovered <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> that appear to be an django stack with added most-used apps so easy and speed up development.</p> <p>I never used or heard of Pinax before and like to know if you have feedback about it. I love Django and would like to understand what are to parts of web dev Pinax helps with and using what tools. </p>
24
2009-09-19T10:28:01Z
1,448,968
<p>I'm about to start using Pinax, and I'm glad I discovered it.</p> <p>Our todo list for the site has a lot of things on it, such as new user sign-up with email verification, discussions, and a news feed for users that blends site-wide updates and updates for that user. We can code all of this up, but it'll take a while. It'd daunting.</p> <p>Luckily, I discovered Pinax. Instead of coding all those features I'll only need to learn the Pinax structure and write some glue. I bet it will take 1/50th of the time that would have been required to write the features we need.</p>
6
2009-09-19T17:02:43Z
[ "python", "django", "pinax" ]
What are the best benefits of using Pinax?
1,448,292
<p>I recently discovered <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> that appear to be an django stack with added most-used apps so easy and speed up development.</p> <p>I never used or heard of Pinax before and like to know if you have feedback about it. I love Django and would like to understand what are to parts of web dev Pinax helps with and using what tools. </p>
24
2009-09-19T10:28:01Z
1,475,696
<p>As the two other posts said, it comes with a lot of pre-packaged apps that take care of common tasks in modern websites. Here's a list of the external apps that come packaged: <a href="https://github.com/pinax/pinax/blob/master/requirements/pinax.txt" rel="nofollow">https://github.com/pinax/pinax/blob/master/requirements/pinax.txt</a></p> <p>It also gives you project templates to start from, which you can see here: <a href="https://github.com/pinax/pinax/tree/master/pinax/projects/" rel="nofollow">https://github.com/pinax/pinax/tree/master/pinax/projects/</a></p> <p>The projects have working default settings in place so that you can run syncdb then runserver to get going immediately, unlike default Django. Its design also encourages you to write your own apps in such a way that they are more reusable. As they put it, "By integrating numerous reusable Django apps to take care of the things that many sites have in common, it lets you focus on what makes your site different."</p> <p>It does have a small learning curve of its own but I've personally been very happy with it and learned a lot more about Django (and git and virtualenv) by using Pinax.</p>
4
2009-09-25T06:17:47Z
[ "python", "django", "pinax" ]
Role-based security with Google App Engine and Python
1,448,308
<p>I would like to ask what is the common way for handling role-based security with Google App Engine, Python?</p> <p>In the app.yaml, there is the "login" section, but available values are only "admin" and "required".</p> <p>How do you normally handle role-based security?</p> <ul> <li>Create the model with two tables: Roles and UserRoles</li> <li>Import values for Roles table</li> <li>Manually add User to UserRoles</li> <li>Check if user is in the right Roles group</li> </ul> <p>Any other idea or any other method for role-based security, please let us know!</p>
5
2009-09-19T10:42:25Z
1,448,733
<p>I would do this by adding a ListProperty for roles to the model representing users. The list contains any roles a given user belongs to. This way if you want to know whether a given user belongs to a given role (I expect, the most common operation), it is a fast membership test.</p> <p>You could put the role names directly into the lists as strings or add a layer of indirection to another entity specifying the details about the role so it is easy to change the details later. But, this has a runtime cost of an additional RPC to fetch the details about the role.</p> <p>The downside to this method comes if you want to remove all users from a given role, or perform any other kind of global operation. I suppose you could mark a role 'deleted', but then you still have data cluttering up all your user models until you clean them up manually. So I am curious to hear what others suggest.</p>
4
2009-09-19T15:10:37Z
[ "python", "google-app-engine", "role-based" ]
Custom storage system for GridFS (MongoDB)?
1,448,386
<p>Can anyone point me to any projects/django apps that provide a plugable custom storage system so I can use GridFS with Django to store file uploads?</p> <p>I've found django-mongodb but it doesnt seem to support GridFS, nor does django-storages.</p> <p>I plan to run mysql for the normal database requrements and only use mongodb for file storage so to be clear I dont want to use mongodb as my main database.</p>
4
2009-09-19T11:38:03Z
1,448,676
<p>I work on PyMongo, the MongoDB Python driver, and haven't heard of any project to provide custom storage for Django using GridFS. This looks like it wouldn't be very hard to write on top of PyMongo: could probably be a direct translation of the <a href="http://api.mongodb.org/python/0.15.2/gridfs-module.html" rel="nofollow">GridFS API</a> onto the <a href="http://docs.djangoproject.com/en/dev/howto/custom-file-storage/" rel="nofollow">Django storage API</a>. Maybe could take a look at throwing something together at some point, but this would be a great open-source project for anybody looking to get involved.</p>
3
2009-09-19T14:40:16Z
[ "python", "django", "mongodb" ]
Custom storage system for GridFS (MongoDB)?
1,448,386
<p>Can anyone point me to any projects/django apps that provide a plugable custom storage system so I can use GridFS with Django to store file uploads?</p> <p>I've found django-mongodb but it doesnt seem to support GridFS, nor does django-storages.</p> <p>I plan to run mysql for the normal database requrements and only use mongodb for file storage so to be clear I dont want to use mongodb as my main database.</p>
4
2009-09-19T11:38:03Z
3,646,343
<p><a href="https://github.com/django-mongodb-engine/mongodb-engine" rel="nofollow">django-mongodb-engine</a> might be worth a look as it enables you to do that without the need to make changes to your existing Django code.</p>
1
2010-09-05T14:13:25Z
[ "python", "django", "mongodb" ]
Custom storage system for GridFS (MongoDB)?
1,448,386
<p>Can anyone point me to any projects/django apps that provide a plugable custom storage system so I can use GridFS with Django to store file uploads?</p> <p>I've found django-mongodb but it doesnt seem to support GridFS, nor does django-storages.</p> <p>I plan to run mysql for the normal database requrements and only use mongodb for file storage so to be clear I dont want to use mongodb as my main database.</p>
4
2009-09-19T11:38:03Z
4,080,640
<p>I recently implemented the <a href="http://schallis.com/2010/oct/18/so-gridfs-mongoengine--django-walk-into-a-bar-/" rel="nofollow">GridFS support in Mongoengine</a> which you might like to checkout. This includes a Django storage backend which you can plug right into you projects and use with ImageField etc. I'm using these technologies in production and it's holding up great so far.</p>
1
2010-11-02T17:59:14Z
[ "python", "django", "mongodb" ]
Custom storage system for GridFS (MongoDB)?
1,448,386
<p>Can anyone point me to any projects/django apps that provide a plugable custom storage system so I can use GridFS with Django to store file uploads?</p> <p>I've found django-mongodb but it doesnt seem to support GridFS, nor does django-storages.</p> <p>I plan to run mysql for the normal database requrements and only use mongodb for file storage so to be clear I dont want to use mongodb as my main database.</p>
4
2009-09-19T11:38:03Z
5,202,247
<p>I needed exactly that for <a href="https://github.com/rosarior/mayan" rel="nofollow">Mayan EDMS</a>, plugable storage and database separation. Using Michael Dirolf's latest PyMongo library, it was rather trivial to get a basic class going.</p> <p>To use it:</p> <pre><code>from gridfsstorage import GridFSStorage file = models.FileField(storage=GridFSStorage()) </code></pre> <p>the gridfsstorage.py file:</p> <pre><code>import os from django.core.files.storage import Storage from django.utils.encoding import force_unicode from django.conf import settings from pymongo import Connection from gridfs import GridFS class GridFSStorage(Storage): def __init__(self, *args, **kwargs): self.db = Connection(host=settings.GRIDFS_HOST, port=settings.GRIDFS_PORT)[settings.DATABASE_NAME] self.fs = GridFS(self.db) def save(self, name, content): while True: try: # This file has a file path that we can move. if hasattr(content, 'temporary_file_path'): self.move(content.temporary_file_path(), name) content.close() # This is a normal uploadedfile that we can stream. else: # This fun binary flag incantation makes os.open throw an # OSError if the file already exists before we open it. newfile = self.fs.new_file(filename=name) try: for chunk in content.chunks(): newfile.write(chunk) finally: newfile.close() except Exception, e: raise else: # OK, the file save worked. Break out of the loop. break return name def open(self, name, *args, **kwars): return self.fs.get_last_version(name) def delete(self, name): oid = self.fs.get_last_version(name)._id self.fs.delete(oid) def exists(self, name): return self.fs.exists(filename=name) def path(self, name): return force_unicode(name) def size(self, name): return self.fs.get_last_version(name).length def move(self, old_file_name, name, chunk_size=1024*64): # first open the old file, so that it won't go away old_file = open(old_file_name, 'rb') try: newfile = self.fs.new_file(filename=name) try: current_chunk = None while current_chunk != '': current_chunk = old_file.read(chunk_size) newfile.write(current_chunk) finally: newfile.close() finally: old_file.close() try: os.remove(old_file_name) except OSError, e: # Certain operating systems (Cygwin and Windows) # fail when deleting opened files, ignore it. (For the # systems where this happens, temporary files will be auto-deleted # on close anyway.) if getattr(e, 'winerror', 0) != 32 and getattr(e, 'errno', 0) != 13: raise </code></pre>
1
2011-03-05T06:54:16Z
[ "python", "django", "mongodb" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
1,448,446
<p>Install mysql and python via <a href="http://guide.macports.org/">Macports</a> The porters have done all the difficult work.</p> <pre><code>sudo port install py26-mysql sudo port install mysql5-server </code></pre> <p>should install what you need. (see <a href="http://stackoverflow.com/questions/1081231/macports-doesnt-install-org-macports-mysql5-plist-with-mysql5-server">Stack overflow for comments re mysql server</a>)</p> <p>If you only need to connect to mysql and not run a server then the first line is sufficient.</p> <p>Macports now (early 2013) will provide binary downloads for common combinations of OS a executable architecture, for others (and if you request it) it will build from source.</p> <p>In general macports (or fink) help when there are complex libraries etc that need to be installed.</p> <p>Python only code and if simple C dependencies can be set up via setuptools etc, but it begins to get complex if you mix the two.</p>
36
2009-09-19T12:17:11Z
[ "python", "mysql", "osx" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
1,448,476
<p>Here is the tale of my rambling experience with this problem. Would love to see it edited or generalised if you have better experience of the issue... apply a bit of that SO magic.</p> <p><strong>Note: Comments in next paragraph applied to Snow Leopard, but not to Lion, which appears to require 64-bit MySQL</strong></p> <p>First off, the author (still?) of MySQLdb says <a href="http://mysql-python.blogspot.com/2008/03/i-am-not-dead.html">here</a> that one of the most pernicious problems is that OS X comes installed with a 32 bit version of Python, but most average joes (myself included) probably jump to install the 64 bit version of MySQL. Bad move... remove the 64 bit version if you have installed it (instructions on this fiddly task are available on SO <a href="http://stackoverflow.com/questions/1436425/how-do-you-uninstall-mysql-from-mac-os-x">here</a>), then download and install the 32 bit version (package <a href="http://dev.mysql.com/downloads/mysql/5.1.html#macosx-dmg">here</a>)</p> <p>There are numerous step-by-steps on how to build and install the MySQLdb libraries. They often have subtle differences. <a href="http://www.mangoorange.com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/">This</a> seemed the most popular to me, and provided the working solution. I've reproduced it with a couple of edits below</p> <p><strong>Step 0:</strong> Before I start, I assume that you have MySQL, Python, and <a href="https://developer.apple.com/downloads/index.action?q=command%20line%20tools">GCC</a> installed on the mac.</p> <p><strong>Step 1:</strong> Download the latest <a href="http://sourceforge.net/projects/mysql-python/files/">MySQL for Python adapter</a> from SourceForge.</p> <p><strong>Step 2:</strong> Extract your downloaded package:</p> <pre><code>tar xzvf MySQL-python-1.2.2.tar.gz </code></pre> <p><strong>Step 3:</strong> Inside the folder, clean the package:</p> <pre><code>sudo python setup.py clean </code></pre> <p>COUPLE OF EXTRA STEPS, (from <a href="http://sourceforge.net/projects/mysql-python/forums/forum/70461/topic/3175684">this comment</a>)</p> <p><strong>Step 3b:</strong> Remove everything under your MySQL-python-1.2.2/build/* directory -- don't trust the "python setup.py clean" to do it for you</p> <p><strong>Step 3c:</strong> Remove the egg under Users/$USER/.python-eggs</p> <p><strong>Step 4:</strong> Originally required editing _mysql.c, but is now NO LONGER NECESSARY. MySQLdb community seem to have fixed this bug now.</p> <p><strong>Step 5:</strong> Create a symbolic link under lib to point to a sub-directory called mysql. This is where it looks for during compilation.</p> <pre><code>sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql </code></pre> <p><strong>Step 6:</strong> Edit the setup_posix.py and change the following</p> <p>mysql_config.path = "mysql_config"</p> <p>to</p> <p>mysql_config.path = "/usr/local/mysql/bin/mysql_config"</p> <p><strong>Step 7:</strong> In the same directory, rebuild your package (ignore the warnings that comes with it)</p> <pre><code>sudo python setup.py build </code></pre> <p><strong>Step 8:</strong> Install the package and you are done.</p> <pre><code>sudo python setup.py install </code></pre> <p><strong>Step 9:</strong> Test if it's working. It works if you can import MySQLdb.</p> <pre><code>python </code></pre> <p>>>> <code>import MySQLdb</code></p> <p><strong>Step 10:</strong> If upon trying to import you receive an error complaining that <code>Library not loaded: libmysqlclient.18.dylib</code> ending with: <code>Reason: image not found</code> you need to create one additional symlink which is:</p> <pre><code>sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib </code></pre> <p>You should then be able to <code>import MySQLdb</code> without any errors.</p> <p>One final hiccup though is that if you start Python from the build directory you will get this error:</p> <p>/Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.5/site-packages/MySQL_python-1.2.3c1-py2.5-macosx-10.5-i386.egg/_mysql.pyc, but XXXX/MySQL-python-1.2.3c1 is being added to sys.path</p> <p>This is pretty easy to Google, but to save you the trouble you will end up <a href="http://cd34.com/blog/">here</a> (or maybe not... not a particularly future-proof URL) and figure out that you need to <code>cd ..</code> out of build directory and the error should disappear.</p> <p>As I wrote at the top, I'd love to see this answer generalised, as there are numerous other specific experiences of this horrible problem out there. Edit away, or provide your own, better answer.</p>
119
2009-09-19T12:37:04Z
[ "python", "mysql", "osx" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
6,025,504
<p>Here's another step I had to go through, after receiving an error on completing Step 9:</p> <pre><code>ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib </code></pre> <p>Reference: Thanks! <a href="http://ageekstory.blogspot.com/2011_04_01_archive.html">http://ageekstory.blogspot.com/2011_04_01_archive.html</a></p>
13
2011-05-17T02:07:24Z
[ "python", "mysql", "osx" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
13,867,261
<p>Just had this problem (again!) after getting a new Lion box.</p> <p>Best solution I've found (still not 100% optimal, but working):</p> <ul> <li><p>make sure you have 64-bit python. <a href="http://stackoverflow.com/questions/3207177/how-to-check-if-a-library-is-32bit-64bit-built-on-mac-os-x">How to check if a library is 32bit/64bit built on Mac OS X?</a></p></li> <li><p>install easy_install if you don't have it. <a href="http://packages.python.org/distribute/easy_install.html" rel="nofollow">http://packages.python.org/distribute/easy_install.html</a></p></li> <li><p>install GCC if you don't have it. </p></li> </ul> <p>you <em>can</em> get it by downloading XCode/Dev Tools from Apple - this is a big download - </p> <p>... but instead I recommend this github which has what you need (and does not have XCode): <a href="https://github.com/kennethreitz/osx-gcc-installer" rel="nofollow">https://github.com/kennethreitz/osx-gcc-installer</a></p> <p>I downloaded their prebuilt PKG for lion, <a href="https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg" rel="nofollow">https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg</a></p> <ul> <li><p>make sure you have downloaded a 64-BIT version of MYSQL Community. (The DMG install is an easy route) <a href="http://dev.mysql.com/downloads/mysql/" rel="nofollow">http://dev.mysql.com/downloads/mysql/</a></p></li> <li><p>Set paths as follows:</p> <p>export PATH=$PATH:/usr/local/mysql-XXXX </p> <p>export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/</p> <p>export ARCHFLAGS='-arch x86_64'</p></li> </ul> <p>NOTE THAT:</p> <blockquote> <p>1 in mysql-XXXX above, XXX is the specific version you downloaded. (Probably /usr/local/mysql/ would also work since this is most likely an alias to the same, but I won't pretend to know your setup)</p> <p>2 I have seen it suggested that ARCHFLAGS be set to '-arch i386 -arch x86_64' but specifying only x86_64 seemed to work better for me. (I can think of some reasons for this but they are not strictly relevant).</p> </blockquote> <ul> <li><p>Install the beast!</p> <p>easy_install MySQL-python</p></li> <li><p>LAST STEP:</p></li> </ul> <p><strong>Permanently add the DYLD_LIBRARY_PATH!</strong> </p> <p>You can add it to your bash_profile or similar. This was the missing step for me, without which my system continued to insist on various errors finding _mysql.so and so on.</p> <p>export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/</p> <p>@richard-boardman, just noticed your soft link solution, which may in effect be doing the same thing my PATH solution does...folks, whatever works best for you.</p> <p>Best reference: <a href="http://activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/" rel="nofollow">http://activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/</a></p>
4
2012-12-13T19:46:17Z
[ "python", "mysql", "osx" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
14,873,391
<p>If you are using 64 bit MySQL, using ARCHFLAGS to specify your cpu architecture while building mysql-python libraries would do the trick:</p> <pre><code>ARCHFLAGS='-arch x86_64' python setup.py build ARCHFLAGS='-arch x86_64' python setup.py install </code></pre>
0
2013-02-14T11:07:38Z
[ "python", "mysql", "osx" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
18,178,419
<p>A quick and easy way for Mac OS X <strong>10.8</strong> (Mountain Lion), <strong>10.9</strong> (Mavericks), <strong>10.10</strong> (Yosemite), and <strong>10.11</strong> (El Capitan):</p> <p>I assume you have XCode, it's <a href="https://stackoverflow.com/questions/9329243/xcode-4-4-and-later-install-command-line-tools">command line tool</a>, Python and MySQL installed.</p> <ol> <li><p>Install PIP:</p> <pre><code>sudo easy_install pip </code></pre></li> <li><p>Edit ~/.profile: <em>(Might not be necessary in Mac OS X 10.10)</em></p> <pre><code>nano ~/.profile </code></pre> <p>Copy and paste the following two line</p> <pre><code>export PATH=/usr/local/mysql/bin:$PATH export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/ </code></pre> <p>Save and exit. Afterwords execute the following command</p> <pre><code>source ~/.profile </code></pre></li> <li><p>Install MySQLdb</p> <pre><code>sudo pip install MySQL-python </code></pre> <p>To test if everything works fine just try</p> <pre><code>python -c "import MySQLdb" </code></pre></li> </ol> <p>It worked like a charm for me. I hope it helps.</p> <p>If you encounter an error regarding a missing library: <em>Library not loaded: libmysqlclient.18.dylib</em> then you have to symlink it to <code>/usr/lib</code> like so:</p> <pre><code>sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib </code></pre>
66
2013-08-12T01:32:58Z
[ "python", "mysql", "osx" ]
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
<p>I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I know that I'm going to need a reference to the solution in future, I'm going to ask the question, provide my answer and see what else floats to the surface.</p> <p>So the question is how to get <a href="http://sourceforge.net/projects/mysql-python/files/">MySQLdb</a> working on Mac OS X?</p>
81
2009-09-19T12:04:41Z
19,769,044
<p>Install pip:</p> <pre><code>sudo easy_install pip </code></pre> <p>Install brew:</p> <pre><code>ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" </code></pre> <p>Install mysql:</p> <pre><code>brew install mysql </code></pre> <p>Install MySQLdb</p> <pre><code>sudo pip install MySQL-python </code></pre> <p>If you have compilation problems, try editing the ~/.profile file like in one of the answers here.</p>
8
2013-11-04T13:46:27Z
[ "python", "mysql", "osx" ]