title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
_lsprof.c profiler behaviour towards python multi-threading
443,082
<p>This is a question about Python native c file _lsprof. How does _lsprof.profile() profiler counts total time spent on a function f in a multi-threaded program if the execution of f is interrupted by another thread? </p> <p>For example:</p> <p>def f():<br /> linef1<br /> linef2<br /> linef3 </p> <p>def g():<br /> lineg1<br /> lineg2 </p> <p>And at the execution we have, f and g not being in the same thread:</p> <p>linef1<br /> linef2<br /> lineg1<br /> linef3<br /> lineg2 </p> <p>Then will the total runtime of f be perceived as the amount of time needed to do: </p> <p>linef1<br /> linef2<br /> linef3 </p> <p>or will it be the effective latency time: </p> <p>linef1<br /> linef2<br /> lineg1<br /> linef3 </p> <p>in the results of _lsprof.profile()? </p>
1
2009-01-14T14:17:20Z
579,883
<p>Quoting from the <a href="http://docs.python.org/library/sys.html#sys.setprofile" rel="nofollow">documentation for setprofile</a>:</p> <blockquote> <p>The function is thread-specific, but there is no way for the profiler to know about context switches between threads, so it does not make sense to use this in the presence of multiple threads.</p> </blockquote>
1
2009-02-23T23:44:13Z
[ "python", "multithreading" ]
_lsprof.c profiler behaviour towards python multi-threading
443,082
<p>This is a question about Python native c file _lsprof. How does _lsprof.profile() profiler counts total time spent on a function f in a multi-threaded program if the execution of f is interrupted by another thread? </p> <p>For example:</p> <p>def f():<br /> linef1<br /> linef2<br /> linef3 </p> <p>def g():<br /> lineg1<br /> lineg2 </p> <p>And at the execution we have, f and g not being in the same thread:</p> <p>linef1<br /> linef2<br /> lineg1<br /> linef3<br /> lineg2 </p> <p>Then will the total runtime of f be perceived as the amount of time needed to do: </p> <p>linef1<br /> linef2<br /> linef3 </p> <p>or will it be the effective latency time: </p> <p>linef1<br /> linef2<br /> lineg1<br /> linef3 </p> <p>in the results of _lsprof.profile()? </p>
1
2009-01-14T14:17:20Z
661,707
<p>Thank you for this answer! Actually I am running one profiler in each context, so the question make sense. From the tests I made the profiler would measure "linef1 linef2 linef3" in the above example.</p>
0
2009-03-19T10:38:35Z
[ "python", "multithreading" ]
Jython, Query multiple columns dynamically
443,224
<p>I am working with a oracle database and Jython.</p> <p>I can get data pulled from the database no problem.</p> <pre><code>results = statement.executeQuery("select %s from %s where column_id = '%s'", % (column, table, id)) </code></pre> <p>This works fine if I want to pull one column of data.</p> <p>Say I wanted to loop threw a list like this:</p> <pre><code>columns = ['column1', 'column2', 'column3', 'column4', 'column5'] </code></pre> <p>So the query ended up looking like this:</p> <pre><code>results = statement.executeQuery("select %s, %s, %s, %s, %s from %s where column_id = '%s'", % (column1, column2, column3, column4, column5, table, id)) </code></pre> <p>How could I do this?</p> <p>The reason I want to achive this is because I may want to pull 6 or 7 columns and I would like to store different queries in a external file.</p> <p>I hope you understand what I mean. If not I will try to re word it as best as I can.</p> <p>Cheers</p> <p>Arthur</p>
1
2009-01-14T14:49:41Z
443,331
<p>You could simply substitute all the columns into your query as a single string, like this:</p> <pre><code>columns = ['column1', 'column2', 'column3', 'column4', 'column5'] results = statement.executeQuery("select %s from %s where column_id = '%s'" % (",".join(columns), table, id)) </code></pre> <p>By the way, this isn't protecting against SQL injection, so I'm assuming the columns, table, and id inputs are program-generated or sanitized.</p>
3
2009-01-14T15:19:30Z
[ "python", "oracle10g", "jython" ]
Why does Paramiko hang if you use it while loading a module?
443,387
<p>Put the following into a file <strong>hello.py</strong> (and <code>easy_install paramiko</code> if you haven't got it):</p> <pre><code>hostname,username,password='fill','these','in' import paramiko c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(hostname=hostname, username=username, password=password) i,o,e = c.exec_command('ls /') print(o.read()) c.close() </code></pre> <p>Fill in the first line appropriately.</p> <p>Now type</p> <pre><code>python hello.py </code></pre> <p>and you'll see some ls output.</p> <p>Now instead type</p> <pre><code>python </code></pre> <p>and then from within the interpreter type</p> <pre><code>import hello </code></pre> <p>and voila! It hangs! It will unhang if you wrap the code in a function <code>foo</code> and do <code>import hello; hello.foo()</code> instead.</p> <p>Why does Paramiko hang when used within module initialization? <strong>How is Paramiko even aware that it's being used during module initialization in the first place?</strong></p>
8
2009-01-14T15:35:25Z
450,895
<p>Paramiko uses separate threads for the underlying transport. You should <em>never</em> have a module that spawns a thread as a side effect of importing. As I understand it, there is a single import lock available, so when a child thread from your module attempts another import, it can block indefinitely, because your main thread still holds the lock. (There are probably other gotchas that I'm not aware of too)</p> <p>In general, modules shouldn't have side effects of any sort when importing, or you're going to get unpredictable results. Just hold off execution with the <code>__name__ == '__main__'</code> trick, and you'll be fine.</p> <p>[EDIT] I can't seem to create a simple test case that reproduces this deadlock. I still assume it's a threading issue with import, because the auth code is waiting for an event that never fires. This may be a bug in paramiko, or python, but the good news is that you shouldn't ever see it if you do things correctly ;)</p> <p>This is a good example why you always want to minimize side effects, and why functional programming techniques are becoming more prevalent.</p>
13
2009-01-16T16:01:36Z
[ "python", "multithreading", "ssh", "module", "paramiko" ]
Why does Paramiko hang if you use it while loading a module?
443,387
<p>Put the following into a file <strong>hello.py</strong> (and <code>easy_install paramiko</code> if you haven't got it):</p> <pre><code>hostname,username,password='fill','these','in' import paramiko c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(hostname=hostname, username=username, password=password) i,o,e = c.exec_command('ls /') print(o.read()) c.close() </code></pre> <p>Fill in the first line appropriately.</p> <p>Now type</p> <pre><code>python hello.py </code></pre> <p>and you'll see some ls output.</p> <p>Now instead type</p> <pre><code>python </code></pre> <p>and then from within the interpreter type</p> <pre><code>import hello </code></pre> <p>and voila! It hangs! It will unhang if you wrap the code in a function <code>foo</code> and do <code>import hello; hello.foo()</code> instead.</p> <p>Why does Paramiko hang when used within module initialization? <strong>How is Paramiko even aware that it's being used during module initialization in the first place?</strong></p>
8
2009-01-14T15:35:25Z
32,875,571
<p>As <a href="https://stackoverflow.com/a/450895/1729555">JimB</a> pointed out it is an <strong>import issue</strong> when python tries to implicitly import the <code>str.decode('utf-8')</code> decoder on first use during an ssh connection attempt. See <em>Analysis</em> section for details.</p> <p>In general, one cannot stress enough that you should avoid having a module automatically spawning new threads on import. If you can, try to avoid magic module code in general as it almost always leads to unwanted side-effects.</p> <ol> <li><p>The easy - and sane - fix for your problem - as already mentioned - is to put your code in a <code>if __name__ == '__main__':</code> body which will only be executed if you execute this specific module and wont be executed when this mmodule is imported by other modules. </p></li> <li><p>(not recommended) Another fix is to just do a dummy str.decode('utf-8') in your code before you call <code>SSHClient.connect()</code> - see analysis below.</p></li> </ol> <p>So whats the root cause of this problem?</p> <p><strong>Analysis (simple password auth)</strong></p> <p><em>Hint: If you want to debug threading in python import and set <code>threading._VERBOSE = True</code></em></p> <ol> <li><code>paramiko.SSHClient().connect(.., look_for_keys=False, ..)</code> implicitly spawns a new thread for your connection. You can also see this if you turn on debug output for <code>paramiko.transport</code>. </li> </ol> <p><code>[Thread-5 ] [paramiko.transport ] DEBUG : starting thread (client mode): 0x317f1d0L</code></p> <ol start="2"> <li><p>this is basically done as part of <code>SSHClient.connect()</code>. When <code>client.py:324::start_client()</code> is called, a lock is created <code>transport.py:399::event=threading.Event()</code> and the thread is started <code>transport.py:400::self.start()</code>. Note that the <code>start()</code> method will then execute the class's <code>transport.py:1565::run()</code> method. </p></li> <li><p><code>transport.py:1580::self._log(..)</code> prints the our log message "starting thread" and then proceeds to <code>transport.py:1584::self._check_banner()</code>.</p></li> <li><p><code>check_banner</code> does one thing. It retrieves the ssh banner (first response from server) <code>transport.py:1707::self.packetizer.readline(timeout)</code> (note that the timeout is just a socket read timeout), checks for a linefeed at the end and otherwise times out. </p></li> <li><p>In case a server banner was received, it attempts to utf-8 decode the response string <code>packet.py:287::return u(buf)</code> and thats where the deadlock happens. The <code>u(s, encoding='utf-8')</code> does a str.decode('utf-i') and implicitly imports <code>encodings.utf8</code> in <code>encodings:99</code> via <code>encodings.search_function</code> ending up in an import deadlock.</p></li> </ol> <p>So a dirty fix would be to just import the utf-8 decoder once in order to not block on that specifiy import due to module import sideeffects. (<code>''.decode('utf-8')</code>)</p> <p><strong>Fix</strong></p> <p><strong>dirty fix</strong> - <em>not recommended</em></p> <pre><code>import paramiko hostname,username,password='fill','these','in' ''.decode('utf-8') # dirty fix c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(hostname=hostname, username=username, password=password) i,o,e = c.exec_command('ls /') print(o.read()) c.close() </code></pre> <p><strong>good fix</strong></p> <pre><code>import paramiko if __name__ == '__main__': hostname,username,password='fill','these','in' c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(hostname=hostname, username=username, password=password) i,o,e = c.exec_command('ls /') print(o.read()) c.close() </code></pre> <p>ref <a href="https://github.com/paramiko/paramiko/issues/104" rel="nofollow">paramiko issue tracker: issue 104</a></p>
2
2015-09-30T21:02:11Z
[ "python", "multithreading", "ssh", "module", "paramiko" ]
Why does Paramiko hang if you use it while loading a module?
443,387
<p>Put the following into a file <strong>hello.py</strong> (and <code>easy_install paramiko</code> if you haven't got it):</p> <pre><code>hostname,username,password='fill','these','in' import paramiko c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(hostname=hostname, username=username, password=password) i,o,e = c.exec_command('ls /') print(o.read()) c.close() </code></pre> <p>Fill in the first line appropriately.</p> <p>Now type</p> <pre><code>python hello.py </code></pre> <p>and you'll see some ls output.</p> <p>Now instead type</p> <pre><code>python </code></pre> <p>and then from within the interpreter type</p> <pre><code>import hello </code></pre> <p>and voila! It hangs! It will unhang if you wrap the code in a function <code>foo</code> and do <code>import hello; hello.foo()</code> instead.</p> <p>Why does Paramiko hang when used within module initialization? <strong>How is Paramiko even aware that it's being used during module initialization in the first place?</strong></p>
8
2009-01-14T15:35:25Z
36,416,687
<p>"".decode("utf-8") didn't work for me, I ended up doing this.</p> <pre><code>from paramiko import py3compat # dirty hack to fix threading import lock (issue 104) by preloading module py3compat.u("dirty hack") </code></pre> <p>I have a wrapper for paramiko with that implemented. <a href="https://github.com/bucknerns/sshaolin" rel="nofollow">https://github.com/bucknerns/sshaolin</a></p>
0
2016-04-05T03:36:47Z
[ "python", "multithreading", "ssh", "module", "paramiko" ]
Django template ifequal comparison of decimals
443,650
<p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
1
2009-01-14T16:27:22Z
444,142
<p>According to <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal" rel="nofollow">this</a>, it seems you can only compare strings. I'd make my own <a href="http://www.mechanicalgirl.com/view/custom-template-tags-in-django/" rel="nofollow">template tag</a> if I were you. </p>
2
2009-01-14T18:30:24Z
[ "python", "django", "django-templates" ]
Django template ifequal comparison of decimals
443,650
<p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
1
2009-01-14T16:27:22Z
448,121
<p>Simplest solution is to define a method on the model which encapsulates the numeric logic and returns the human-friendly string.</p> <p>Or you can write a template tag to do it, which is a lot more code, but perhaps preserves the model/view layer separation a bit better.</p>
0
2009-01-15T19:30:01Z
[ "python", "django", "django-templates" ]
Django template ifequal comparison of decimals
443,650
<p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
1
2009-01-14T16:27:22Z
999,518
<p>It's not quite clear if this would help Ardesco but there is <a href="http://code.google.com/p/django-template-utils/" rel="nofollow">template_utils</a> which has <code>if_greater</code>, <code>if_greater_or_equal</code>, <code>if_less</code>, <code>if_less_or_equal</code> tags (among others) which solve very related cases where a plain <code>ifequals</code> isn't quite enough.</p> <p>after installing just add <code>template_utils</code> do your django settings.py under <code>INSTALLED_APPS</code> and then put <code>{% load comparison %}</code> in your template</p>
0
2009-06-16T04:05:00Z
[ "python", "django", "django-templates" ]
Django template ifequal comparison of decimals
443,650
<p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
1
2009-01-14T16:27:22Z
2,644,432
<p>It is not a bug and <strong>it is possible</strong> to achieve what you're trying to do. </p> <p>However, first of all few remarks about your code:</p> <ul> <li>There is no "ifequals/endifequals" operator. You either use <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal">"ifequal/endifequal"</a> or <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#operator">"if/endif"</a>.</li> <li>Second thing. Your code <code>{% ifequal item.number {{key}} %}</code> would cause TemplateSyntaxError Exception if you leave double curly brackets inside the "ifequal" or "if" operator.</li> </ul> <p><strong>Now the solution</strong>:</p> <ol> <li>Just simply use <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat">"stringformat"</a> filter to convert your decimal values to string.</li> <li>Skip curly brackets when you use variables inside operators.</li> <li>Don't forget that variable inside an "if" or "ifequal" operator is always represented as a string.</li> </ol> <p>Here is an <em>example</em>:</p> <pre><code>{% for item in decimals %} {% if item|stringformat:"s" == variable %} {{ variable }} {% endif %} {% endfor %} </code></pre>
11
2010-04-15T10:25:19Z
[ "python", "django", "django-templates" ]
Django template ifequal comparison of decimals
443,650
<p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
1
2009-01-14T16:27:22Z
3,360,593
<p>The solution:</p> <pre><code>{% for item in decimals %} {% if item|stringformat:"s" == variable %} {{ variable }} {% endif %} {% endfor %} </code></pre> <p>works well for comparing a decimal (like the loop) to a string (like a passed value)</p>
2
2010-07-29T08:21:57Z
[ "python", "django", "django-templates" ]
Django template ifequal comparison of decimals
443,650
<p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
1
2009-01-14T16:27:22Z
26,768,872
<p>In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"> >> </a> </p> <p>E.g. if you </p> <pre><code>print Decimal(3.59) </code></pre> <p>you get </p> <pre><code>3.589999999999999857891452847979962825775146484375 </code></pre> <p>So if you compare two decimals in django template, better to use the answer that @Oleg Sakharov has, or alternatively you can use same method but different formatting string like:</p> <pre><code>if item|stringformat:".2f" == "3.59" </code></pre>
0
2014-11-05T23:05:36Z
[ "python", "django", "django-templates" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,833
<p>That isn't possible. You seem to be confusing variables and objects.</p> <p>In any case there may well not be a variable:</p> <p>e.g.</p> <pre><code>foo(Class()) Class().arbitraryMethod() </code></pre> <p>Or multiple:</p> <pre><code>a = b = Class() </code></pre>
0
2009-01-14T17:04:52Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,835
<p>I am unaware of a way to access a variable's name programmatically without using deep reflection and a debugger. I do not think the information is available at runtime.</p> <p>If you want to give instances a (unique?) name, you should probably make the initializer accept an extra argument.</p> <pre><code>def __init__(self, name): self.name = name </code></pre> <p>And the caller should pass in the appropriate name:</p> <pre><code>c = Class("c") </code></pre>
1
2009-01-14T17:05:25Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,836
<p>You can't (short of incredible hacks like examining the stack frame and inspecting the bytecode). There may not even <em>be</em> a name, or there could be multiple such names. What should be given for the following code fragments for instance:</p> <pre><code>l = [Class(), Class()] a=b=c=d=Class() </code></pre>
2
2009-01-14T17:05:28Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,839
<p>I don't think this would be possible because the assignment to the variable of your new instance occours after the object is fully constructed and initialized and so you don't know the variable name it will be assigned to within <strong>init</strong> method</p>
2
2009-01-14T17:06:06Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,841
<p>You can't do this. The reason for this is that the object of the class is created first, and only afterwards is this object bound to the name of the instance.</p>
3
2009-01-14T17:07:24Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,843
<p>This is a scope issue, you can't do what you're asking. Because c would be declared outside your class' scope, your instance is unaware of what its been named in code.</p> <p>Perhaps if you can provide a broader explanation of what you're trying to accomplish a better solution can be suggested.</p>
1
2009-01-14T17:07:36Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
443,868
<p>Python doesn't have variables, it has <a href="http://effbot.org/zone/python-objects.htm" rel="nofollow">objects and names</a>. When you do </p> <pre><code>c = Class() </code></pre> <p>you're doing two things:</p> <ol> <li>Creating a new object of type <code>Class</code></li> <li>Binding the object to the name <code>c</code> in the current scope.</li> </ol> <p>The object you created doesn't have any concept of a "variable name" -- If later you do</p> <pre><code>a = c </code></pre> <p>then the same object is accessible in exactly the same way using the names <code>a</code> and <code>c</code>. You can delete the name <code>a</code>, and the object would still exist.</p> <p>If the objects you create need to have a name, the best way is to pass it to them <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">explicitly</a>, </p> <pre><code>class Class(object): def __init__(self, name): self.name = name var = Class('var') </code></pre>
7
2009-01-14T17:13:51Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
444,624
<p>To persist data objects you need to use the database record's unique ID.</p> <p><strong>pesudo code because I don't know what database module you're using</strong></p> <pre><code>import db # assume this is your db module class Class(object): def __init__(self): self.id = None self.name = None def get_by_id(self, id): records = db.execute('select * from table where id=%s' % str(id)) if records: self.id = records[0]['id'] self.name = records[0]['name'] def save(self): db.execute('update table set name=%s where id=%s' % (self.name, str(self.id))) </code></pre> <p>Again, this is pseudo code, the string injection technique I'm using is NOT advised as its fairly insecure, its just there to illustrate how to persist using classes with a db.</p>
1
2009-01-14T20:55:08Z
[ "python", "instance", "instantiation" ]
Addressing instance name string in __init__(self) in Python
443,775
<p>I am doing something like this:</p> <pre><code>class Class(object): def __init__(self): self.var=#new instance name string# </code></pre> <p>How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:</p> <pre><code>c=Class() </code></pre> <p>I want c.var equal to 'c'.</p> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p> <hr> <p>Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:</p> <pre><code>c=Class() </code></pre> <p>Then, suppose:</p> <pre><code>del c </code></pre> <p>Later on:</p> <pre><code>c=Class() </code></pre> <p>sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.</p>
4
2009-01-14T16:55:48Z
2,160,512
<p>I have the same thought several years ago. This is somekind of neat feature, but the language creator doesn't provide it. And I thought they are all fool to not discover this great feature.</p> <p>But then come to think about that. I think the logic is impossible. say:</p> <pre><code>class Class(object): def __init__(self): self.instance_name.move() # self.instance_name refer to var def move(self): print "move" var = Class() </code></pre> <p>now if the var is an array is that possible too ?</p> <pre><code>var[0] = Class() # i think it will get confused a bit </code></pre> <p>that's what i think of, i don't think that assigning the instance into itself is possible. and in some language I just sent the instance string into the object then using eval to execute the function</p>
0
2010-01-29T07:25:39Z
[ "python", "instance", "instantiation" ]
python, index errors
443,813
<p>I've got some code which draws data from an xml file but it seems to have randomly starting throwing;</p> <pre><code>Traceback (most recent call last): File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in &lt;module&gt; unitCount = getText(evoNode.getElementsByTagName("count")[0].childNodes) IndexError: list index out of range </code></pre> <p>it was fine for the first couple of times I ran it then, I dunno if I changed it or not by accident, but now it's throwing the error.</p> <p>This is an example of the section of the xml it's trying to use;</p> <pre><code>- &lt;unit&gt; &lt;count&gt;1200&lt;/count&gt; &lt;type&gt;Zweihander Doppelsoldners&lt;/type&gt; &lt;typeid&gt;102&lt;/typeid&gt; &lt;/unit&gt; </code></pre> <p>and here's the code that it's complains about;</p> <pre><code> for unitNode in node.getElementsByTagName('unit'): unitName = getText(evoNode.getElementsByTagName("type")[0].childNodes) unitId = getText(evoNode.getElementsByTagName("typeid")[0].childNodes) unitCount = getText(evoNode.getElementsByTagName("count")[0].childNodes) unitList.append("%s x %s" % (unitName, unitCount)) </code></pre> <p>While I accept that it complains about the count line first because count is the highest of the three on the xml file in the units section I'm still not sure why it's complaining, given that it succesfully runs a very similar set of code from which that was cloned and editted.</p> <p>Anyone know what I can do or can suggest ways to refine the question?</p>
1
2009-01-14T17:01:45Z
443,845
<p>A simple idea: check if <code>evoNode.getElementsByTagName("count")</code> returns a non-empty list:</p> <pre><code>counts = evoNode.getElementsByTagName("count") if counts: unitCount = getText(counts[0].childNodes) </code></pre> <p>Of course, the check should be applied to all the lists retrieved by your code.</p> <p>One Other thing, you iterate using <strong><code>unitNode</code></strong>, but inside the loop, you access <strong><code>evoNode</code></strong>, which is probably the same for every iteration.</p>
2
2009-01-14T17:08:01Z
[ "python", "xml", "for-loop" ]
python, index errors
443,813
<p>I've got some code which draws data from an xml file but it seems to have randomly starting throwing;</p> <pre><code>Traceback (most recent call last): File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in &lt;module&gt; unitCount = getText(evoNode.getElementsByTagName("count")[0].childNodes) IndexError: list index out of range </code></pre> <p>it was fine for the first couple of times I ran it then, I dunno if I changed it or not by accident, but now it's throwing the error.</p> <p>This is an example of the section of the xml it's trying to use;</p> <pre><code>- &lt;unit&gt; &lt;count&gt;1200&lt;/count&gt; &lt;type&gt;Zweihander Doppelsoldners&lt;/type&gt; &lt;typeid&gt;102&lt;/typeid&gt; &lt;/unit&gt; </code></pre> <p>and here's the code that it's complains about;</p> <pre><code> for unitNode in node.getElementsByTagName('unit'): unitName = getText(evoNode.getElementsByTagName("type")[0].childNodes) unitId = getText(evoNode.getElementsByTagName("typeid")[0].childNodes) unitCount = getText(evoNode.getElementsByTagName("count")[0].childNodes) unitList.append("%s x %s" % (unitName, unitCount)) </code></pre> <p>While I accept that it complains about the count line first because count is the highest of the three on the xml file in the units section I'm still not sure why it's complaining, given that it succesfully runs a very similar set of code from which that was cloned and editted.</p> <p>Anyone know what I can do or can suggest ways to refine the question?</p>
1
2009-01-14T17:01:45Z
443,871
<p>As gimel said you should check getElementsByTagName("count") if it returns non empty list, but back to your problem:</p> <p>If you said that it was working before then my guess that the problem is with the source where you get the XML.</p>
1
2009-01-14T17:14:38Z
[ "python", "xml", "for-loop" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
443,934
<p>Personally, I've only seen callbacks used. However, I haven't seen that much event driven python code so YMMV.</p>
0
2009-01-14T17:34:58Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
443,972
<p>I can't speak for common approaches, but <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html" rel="nofollow" title="Patterns in Python">this page</a> (actual copy is unavailable) has an implementation of the observer pattern that I like.</p> <p>Here's the Internet Archive link: <a href="http://web.archive.org/web/20060612061259/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html" rel="nofollow">http://web.archive.org/web/20060612061259/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html</a></p>
3
2009-01-14T17:43:22Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
444,003
<p>I have seen listeners and callbacks used. But AFAIK there is no Python way. They should be equally feasible if the application in question is suitable.</p>
0
2009-01-14T17:50:22Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
444,057
<p>Personally I don't see a difference between callbacks, listeners, and delegates.</p> <p>The <a href="http://en.wikipedia.org/wiki/Observer_pattern">observer pattern</a> (a.k.a listeners, a.k.a "multiple callbacks") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the <code>__call__</code> magic method. All you have to do is define the interface you expect from these - e.g. do they receive any parameters.</p> <pre><code>class Foo(object): def __init__(self): self._bar_observers = [] def add_bar_observer(self, observer): self._bar_observers.append(observer) def notify_bar(self, param): for observer in self._bar_observers: observer(param) def observer(param): print "observer(%s)" % param class Baz(object): def observer(self, param): print "Baz.observer(%s)" % param class CallableClass(object): def __call__(self, param): print "CallableClass.__call__(%s)" % param baz = Baz() foo = Foo() foo.add_bar_observer(observer) # function foo.add_bar_observer(baz.observer) # bound method foo.add_bar_observer(CallableClass()) # callable instance foo.notify_bar(3) </code></pre>
14
2009-01-14T18:07:35Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
444,108
<p>It all depends on the level of complexity your application requires. For simple events, callbacks will probably do. For more complex patterns and decoupled levels you should use some kind of a publish-subscribe implementation, such as <a href="http://pydispatcher.sourceforge.net/" rel="nofollow">PyDispatcher</a> or wxPython's pubsub.</p> <p>See also <a href="http://stackoverflow.com/questions/115844/recommended-python-publish-subscribe-dispatch-module">this discussion</a>.</p>
1
2009-01-14T18:20:02Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
444,154
<p>Most of the Python libraries I have used implement a callback model for their event notifications, which I think suits the language fairly well. <a href="http://www.pygtk.org/" rel="nofollow">Pygtk</a> does this by deriving all objects from <a href="http://www.pygtk.org/docs/pygobject/class-gobject.html" rel="nofollow">GObject</a>, which implements callback-based signal handling. (Although this is a feature of the underlying C GTK implementation, not something inspired by the language.) However, <a href="http://sourceforge.net/projects/pygtkmvc/" rel="nofollow">Pygtkmvc</a> does an interesting job of implementing an observer pattern (and MVC) over the top of Pygtk. It uses a very ornate metaclass based implementation, but I have found that it works fairly well for most cases. The code is reasonably straightforward to follow, as well, if you are interested in seeing one way in which this has been done.</p>
1
2009-01-14T18:33:55Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
445,865
<p>The <code>matplotlib.cbook</code> module contains a class <code>CallbackRegistry</code> that you might want to have a look at. From the <a href="http://matplotlib.sourceforge.net/api/cbook_api.html" rel="nofollow">documentation</a>:</p> <pre> Handle registering and disconnecting for a set of signals and callbacks: signals = 'eat', 'drink', 'be merry' def oneat(x): print 'eat', x def ondrink(x): print 'drink', x callbacks = CallbackRegistry(signals) ideat = callbacks.connect('eat', oneat) iddrink = callbacks.connect('drink', ondrink) #tmp = callbacks.connect('drunk', ondrink) # this will raise a ValueError callbacks.process('drink', 123) # will call oneat callbacks.process('eat', 456) # will call ondrink callbacks.process('be merry', 456) # nothing will be called callbacks.disconnect(ideat) # disconnect oneat callbacks.process('eat', 456) # nothing will be called </pre> <p>You probably do not want a dependency to the matplotlib package. I suggest you simply copy-paste the class into your own module from the <a href="http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/lib/matplotlib/cbook.py?view=markup" rel="nofollow">source code</a>.</p>
0
2009-01-15T06:39:56Z
[ "python", "events", "delegates", "callback" ]
Python: Callbacks, Delegates, ... ? What is common?
443,885
<p>Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on. Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>
21
2009-01-14T17:20:28Z
851,099
<p>I'm searching for an implementation to register and handle events in Python. My only experience is with <a href="http://www.pygtk.org/docs/pygobject/class-gobject.html" rel="nofollow">Gobject</a>, but have only used it with PyGtk. It is flexible, but might be overly complicated for some users. I have come across of few other interesting candidates as well, but it's not clear how exactly they compare to one another.</p> <ul> <li><a href="http://code.google.com/p/pyevent/" rel="nofollow">Pyevent</a>, a wrapper around <a href="http://code.google.com/p/pyevent/" rel="nofollow">libevent</a>.</li> <li><a href="http://code.google.com/p/pyevent/" rel="nofollow">Zope Event</a></li> </ul>
0
2009-05-12T04:13:31Z
[ "python", "events", "delegates", "callback" ]
Why don't Django admin "Today" and "Now" buttons show up in Safari?
443,920
<p>I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png" alt="alt text" /></p> <p>This is as expected. However, when I deploy to my webserver and use the application from there, I get this:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png" alt="alt text" /></p> <p>The application on the server is <em>exactly</em> the same as my local copy, <em>except</em> that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?</p> <p><hr /></p> <h2>Update</h2> <ul> <li>The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).</li> <li>I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget: <ul> <li><code>RelatedObjectLookup.js</code></li> <li><code>DateTimeShortcuts.js</code></li> <li><code>icon_calendar.gif</code></li> <li><code>icon_clock.gif</code></li> </ul></li> </ul>
3
2009-01-14T17:30:34Z
443,992
<p>Check the media location, permissions and setup on your deployment server.</p> <p><a href="http://www.djangobook.com/en/1.0/chapter20/" rel="nofollow">http://www.djangobook.com/en/1.0/chapter20/</a></p>
0
2009-01-14T17:47:43Z
[ "javascript", "python", "django", "safari", "webkit" ]
Why don't Django admin "Today" and "Now" buttons show up in Safari?
443,920
<p>I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png" alt="alt text" /></p> <p>This is as expected. However, when I deploy to my webserver and use the application from there, I get this:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png" alt="alt text" /></p> <p>The application on the server is <em>exactly</em> the same as my local copy, <em>except</em> that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?</p> <p><hr /></p> <h2>Update</h2> <ul> <li>The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).</li> <li>I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget: <ul> <li><code>RelatedObjectLookup.js</code></li> <li><code>DateTimeShortcuts.js</code></li> <li><code>icon_calendar.gif</code></li> <li><code>icon_clock.gif</code></li> </ul></li> </ul>
3
2009-01-14T17:30:34Z
444,015
<p>It seems like you have admin media missing (hence js and images aren't loading). I generally do following.</p> <p>in <code>settings.py</code></p> <pre><code>ADMIN_MEDIA_PREFIX = '/media/admin/' </code></pre> <p>Then I symlink path of <code>django.contrib.admin.media</code> within my <code>media</code> dir. Say:</p> <pre><code>ln -s /var/lib/python-support/python2.5/django/contrib/admin/media/ /var/www/media/admin </code></pre> <p>Development server serves admin media automatically. But on production servers one generally prefers to server static stuff directly from apache (or whatever server).</p>
1
2009-01-14T17:55:36Z
[ "javascript", "python", "django", "safari", "webkit" ]
Why don't Django admin "Today" and "Now" buttons show up in Safari?
443,920
<p>I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png" alt="alt text" /></p> <p>This is as expected. However, when I deploy to my webserver and use the application from there, I get this:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png" alt="alt text" /></p> <p>The application on the server is <em>exactly</em> the same as my local copy, <em>except</em> that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?</p> <p><hr /></p> <h2>Update</h2> <ul> <li>The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).</li> <li>I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget: <ul> <li><code>RelatedObjectLookup.js</code></li> <li><code>DateTimeShortcuts.js</code></li> <li><code>icon_calendar.gif</code></li> <li><code>icon_clock.gif</code></li> </ul></li> </ul>
3
2009-01-14T17:30:34Z
444,052
<p>Have you tried checking out firebug's NET tab to see if the admin javascript/css/image files are all loading correctly?</p> <p>I had that problem once.</p> <p>Compare all those files from the dev server against the production server.</p>
0
2009-01-14T18:06:30Z
[ "javascript", "python", "django", "safari", "webkit" ]
Why don't Django admin "Today" and "Now" buttons show up in Safari?
443,920
<p>I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png" alt="alt text" /></p> <p>This is as expected. However, when I deploy to my webserver and use the application from there, I get this:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png" alt="alt text" /></p> <p>The application on the server is <em>exactly</em> the same as my local copy, <em>except</em> that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?</p> <p><hr /></p> <h2>Update</h2> <ul> <li>The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).</li> <li>I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget: <ul> <li><code>RelatedObjectLookup.js</code></li> <li><code>DateTimeShortcuts.js</code></li> <li><code>icon_calendar.gif</code></li> <li><code>icon_clock.gif</code></li> </ul></li> </ul>
3
2009-01-14T17:30:34Z
636,182
<p>If you're getting 304 on those files. Flush your browser's cache and try again.</p> <p>If it doesn't load again anyway, make sure you are getting 200 OK.</p>
2
2009-03-11T20:19:08Z
[ "javascript", "python", "django", "safari", "webkit" ]
Why don't Django admin "Today" and "Now" buttons show up in Safari?
443,920
<p>I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png" alt="alt text" /></p> <p>This is as expected. However, when I deploy to my webserver and use the application from there, I get this:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png" alt="alt text" /></p> <p>The application on the server is <em>exactly</em> the same as my local copy, <em>except</em> that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?</p> <p><hr /></p> <h2>Update</h2> <ul> <li>The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).</li> <li>I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget: <ul> <li><code>RelatedObjectLookup.js</code></li> <li><code>DateTimeShortcuts.js</code></li> <li><code>icon_calendar.gif</code></li> <li><code>icon_clock.gif</code></li> </ul></li> </ul>
3
2009-01-14T17:30:34Z
648,681
<p>I think you have to look at what is different between your firefox configuration and safary config</p> <p>Off the top of my head:</p> <ul> <li><p>One could be configured to use a proxy (messing with the trafic) the other not. Make sure the configuration is the same in both.</p></li> <li><p>Safari could have cached the error clear the cache before testing again.</p></li> <li><p>Try to access the gif files directly from the browser (by inputting the full url of the images) and run wireshark on the wire comparing both GET requests and responses. Something WILL be different that will help you to track the problem.</p></li> </ul>
3
2009-03-15T22:25:08Z
[ "javascript", "python", "django", "safari", "webkit" ]
How to create python bytes object from long hex string?
443,967
<p>I have a long sequence of hex digits in a string, such as </p> <blockquote> <p>000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44</p> </blockquote> <p>only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?</p>
39
2009-01-14T17:42:50Z
443,985
<p>Try the <a href="http://doc.astro-wise.org/binascii.html#-unhexlify">binascii module</a></p> <pre><code>from binascii import unhexlify b = unhexlify(myhexstr) </code></pre>
26
2009-01-14T17:46:38Z
[ "python", "hex", "byte" ]
How to create python bytes object from long hex string?
443,967
<p>I have a long sequence of hex digits in a string, such as </p> <blockquote> <p>000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44</p> </blockquote> <p>only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?</p>
39
2009-01-14T17:42:50Z
443,990
<p>You can do this with the hex codec. ie:</p> <pre><code>&gt;&gt;&gt; s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44' &gt;&gt;&gt; s.decode('hex') '\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD' </code></pre>
37
2009-01-14T17:47:20Z
[ "python", "hex", "byte" ]
How to create python bytes object from long hex string?
443,967
<p>I have a long sequence of hex digits in a string, such as </p> <blockquote> <p>000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44</p> </blockquote> <p>only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?</p>
39
2009-01-14T17:42:50Z
444,005
<pre><code>result = bytes.fromhex(some_hex_string) </code></pre>
21
2009-01-14T17:50:38Z
[ "python", "hex", "byte" ]
How to create python bytes object from long hex string?
443,967
<p>I have a long sequence of hex digits in a string, such as </p> <blockquote> <p>000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44</p> </blockquote> <p>only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?</p>
39
2009-01-14T17:42:50Z
17,160,152
<p>Works in Python 2.7 and higher including python3:</p> <pre><code>result = bytearray.fromhex('deadbeef') </code></pre> <p><strong>Note:</strong> There seems to be a bug with the <code>bytearray.fromhex()</code> function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown: </p> <pre><code>&gt;&gt;&gt; bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: fromhex() argument 1 must be unicode, not str` </code></pre>
18
2013-06-18T03:37:20Z
[ "python", "hex", "byte" ]
How to create python bytes object from long hex string?
443,967
<p>I have a long sequence of hex digits in a string, such as </p> <blockquote> <p>000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44</p> </blockquote> <p>only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?</p>
39
2009-01-14T17:42:50Z
29,030,879
<pre><code>import binascii binascii.b2a_hex(obj) </code></pre>
-1
2015-03-13T11:19:26Z
[ "python", "hex", "byte" ]
python - readable list of objects
444,058
<p>This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;</p> <pre><code>&lt;__main__.evolutions instance at 0x01B8EA08&gt; </code></pre> <p>but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?</p>
5
2009-01-14T18:07:54Z
444,070
<p>Checkout the __str__() and __repr__() methods.</p> <p>See <a href="http://docs.python.org/reference/datamodel.html#object.__repr__" rel="nofollow">http://docs.python.org/reference/datamodel.html#object.__repr__</a></p>
4
2009-01-14T18:11:47Z
[ "python", "list" ]
python - readable list of objects
444,058
<p>This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;</p> <pre><code>&lt;__main__.evolutions instance at 0x01B8EA08&gt; </code></pre> <p>but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?</p>
5
2009-01-14T18:07:54Z
444,071
<p>You'll want to override your class's "to string" method:</p> <pre><code>class Foo: def __str__(self): return "String representation of me" </code></pre>
4
2009-01-14T18:11:54Z
[ "python", "list" ]
python - readable list of objects
444,058
<p>This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;</p> <pre><code>&lt;__main__.evolutions instance at 0x01B8EA08&gt; </code></pre> <p>but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?</p>
5
2009-01-14T18:07:54Z
444,073
<p>If you want to just display a particular attribute of each class instance, you can do</p> <pre><code>print([obj.attr for obj in my_list_of_objs]) </code></pre> <p>Which will print out the <code>attr</code> attribute of each object in the list <code>my_list_of_objs</code>. Alternatively, you can define the <code>__str__()</code> method for your class, which specifies how to convert your objects into strings:</p> <pre><code>class evolutions: def __str__(self): # return string representation of self print(my_list_of_objs) # each object is now printed out according to its __str__() method </code></pre>
8
2009-01-14T18:12:20Z
[ "python", "list" ]
python - readable list of objects
444,058
<p>This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;</p> <pre><code>&lt;__main__.evolutions instance at 0x01B8EA08&gt; </code></pre> <p>but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?</p>
5
2009-01-14T18:07:54Z
444,105
<p>You need to override either the <a href="http://docs.python.org/reference/datamodel.html#object.__str__" rel="nofollow"><code>__str__</code></a>, or <a href="http://docs.python.org/reference/datamodel.html#object.__repr__" rel="nofollow"><code>__repr__</code></a> methods of your object[s]</p>
2
2009-01-14T18:19:54Z
[ "python", "list" ]
python - readable list of objects
444,058
<p>This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;</p> <pre><code>&lt;__main__.evolutions instance at 0x01B8EA08&gt; </code></pre> <p>but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?</p>
5
2009-01-14T18:07:54Z
803,845
<p>My preference is to define a <code>__repr__</code> function that can reconstruct the object (whenever possible). Unless you have a <code>__str__</code> as well, both <code>repr()</code> and <code>str()</code> will call this method.</p> <p>So for example</p> <pre><code>class Foo(object): def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return 'Foo(%r, %r)' % (self.a, self.b) </code></pre> <p>Doing it this way, you have a readable string version, and as a bonus it can be eval'ed to get a copy of the original object.</p> <pre><code>x = Foo(5, 1 + 1) y = eval(str(x)) print y -&gt; Foo(5, 2) </code></pre>
1
2009-04-29T19:17:38Z
[ "python", "list" ]
sqlalchemy, turning a list of IDs to a list of objects
444,475
<p>I have sequence of IDs I want to retrieve. It's simple:</p> <pre><code>session.query(Record).filter(Record.id.in_(seq)).all() </code></pre> <p>Is there a better way to do it?</p>
17
2009-01-14T20:08:32Z
444,524
<p>I'd recommend to take a look at the SQL it produces. You can just print str(query) to see it.</p> <p>I'm not aware of an ideal way of doing it with standard SQL.</p>
1
2009-01-14T20:21:40Z
[ "python", "sqlalchemy" ]
sqlalchemy, turning a list of IDs to a list of objects
444,475
<p>I have sequence of IDs I want to retrieve. It's simple:</p> <pre><code>session.query(Record).filter(Record.id.in_(seq)).all() </code></pre> <p>Is there a better way to do it?</p>
17
2009-01-14T20:08:32Z
457,057
<p>Your code is absolutety fine. </p> <p><code>IN</code> is like a bunch of <code>X=Y</code> joined with <code>OR</code> and is pretty fast in contemporary databases. </p> <p>However, if your list of IDs is long, you could make the query a bit more efficient by passing a sub-query returning the list of IDs.</p>
10
2009-01-19T09:49:39Z
[ "python", "sqlalchemy" ]
sqlalchemy, turning a list of IDs to a list of objects
444,475
<p>I have sequence of IDs I want to retrieve. It's simple:</p> <pre><code>session.query(Record).filter(Record.id.in_(seq)).all() </code></pre> <p>Is there a better way to do it?</p>
17
2009-01-14T20:08:32Z
21,267,667
<p>If you use composite primary keys, you can use <code>tuple_</code>, as in</p> <pre><code>from sqlalchemy import tuple_ session.query(Record).filter(tuple_(Record.id1, Record.id2).in_(seq)).all() </code></pre> <p>Note that this is not available on SQLite (see <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.expression.tuple_" rel="nofollow">doc</a>).</p>
1
2014-01-21T19:49:20Z
[ "python", "sqlalchemy" ]
sqlalchemy, turning a list of IDs to a list of objects
444,475
<p>I have sequence of IDs I want to retrieve. It's simple:</p> <pre><code>session.query(Record).filter(Record.id.in_(seq)).all() </code></pre> <p>Is there a better way to do it?</p>
17
2009-01-14T20:08:32Z
21,267,811
<p>There is one other way; If it's reasonable to expect that the objects in question are already loaded into the session; you've accessed them before in the same transaction, you can instead do:</p> <pre><code>map(session.query(Record).get, seq) </code></pre> <p>In the case where those objects are already present, this will be much faster, since there won't be any queries to retrieve those objects; On the other hand, if more than a tiny number of those objects are <em>not</em> loaded, it will be much, much slower, since it will cause a query per missing instance, instead of a single query for all objects.</p> <p>This can be useful when you are doing <code>joinedload()</code> queries before reaching the above step, so you can be sure that they have been loaded already. In general, you should use the solution in the question by default, and only explore this solution when you have seen that you are querying for the same objects over and over.</p>
1
2014-01-21T19:57:52Z
[ "python", "sqlalchemy" ]
sqlalchemy, turning a list of IDs to a list of objects
444,475
<p>I have sequence of IDs I want to retrieve. It's simple:</p> <pre><code>session.query(Record).filter(Record.id.in_(seq)).all() </code></pre> <p>Is there a better way to do it?</p>
17
2009-01-14T20:08:32Z
28,370,511
<p>The code as is is completely fine. However, someone is asking me for some system of hedging between the two approaches of doing a big IN vs. using get() for individual IDs.</p> <p>If someone is really trying to avoid the SELECT, then the best way to do that is to set up the objects you need in memory ahead of time. Such as, you're working on a large table of elements. Break up the work into chunks, such as, order the full set of work by primary key, or by date range, whatever, then load everything for that chunk locally into a cache:</p> <pre><code> all_ids = [&lt;huge list of ids&gt;] all_ids.sort() while all_ids: chunk = all_ids[0:1000] # bonus exercise! Throw each chunk into a multiprocessing.pool()! all_ids = all_ids[1000:] my_cache = dict( Session.query(Record.id, Record).filter( Record.id.between(chunk[0], chunk[-1])) ) for id_ in chunk: my_obj = my_cache[id_] &lt;work on my_obj&gt; </code></pre> <p>That's the real world use case.</p> <p>But to also illustrate some SQLAlchemy API, we can make a function that does the IN for records we don't have and a local get for those we do. Here is that:</p> <pre><code>from sqlalchemy import inspect def get_all(session, cls, seq): mapper = inspect(cls) lookup = set() for ident in seq: key = mapper.identity_key_from_primary_key((ident, )) if key in session.identity_map: yield session.identity_map[key] else: lookup.add(ident) if lookup: for obj in session.query(cls).filter(cls.id.in_(lookup)): yield obj </code></pre> <p>Here is a demonstration:</p> <pre><code>from sqlalchemy import Column, Integer, create_engine, String from sqlalchemy.orm import Session from sqlalchemy.ext.declarative import declarative_base import random Base = declarative_base() class A(Base): __tablename__ = 'a' id = Column(Integer, primary_key=True) data = Column(String) e = create_engine("sqlite://", echo=True) Base.metadata.create_all(e) ids = range(1, 50) s = Session(e) s.add_all([A(id=i, data='a%d' % i) for i in ids]) s.commit() s.close() already_loaded = s.query(A).filter(A.id.in_(random.sample(ids, 10))).all() assert len(s.identity_map) == 10 to_load = set(random.sample(ids, 25)) all_ = list(get_all(s, A, to_load)) assert set(x.id for x in all_) == to_load </code></pre>
4
2015-02-06T16:37:32Z
[ "python", "sqlalchemy" ]
How are debug consoles implemented in Python?
444,509
<p>I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.</p> <p>Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!</p>
10
2009-01-14T20:17:06Z
444,918
<p>You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory.</p>
6
2009-01-14T22:18:13Z
[ "python", "debugging", "interactive" ]
How are debug consoles implemented in Python?
444,509
<p>I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.</p> <p>Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!</p>
10
2009-01-14T20:17:06Z
445,020
<p><a href="http://docs.python.org/3.0/library/functions.html#input" rel="nofollow">http://docs.python.org/3.0/library/functions.html#input</a><br> <a href="http://docs.python.org/3.0/library/functions.html#eval" rel="nofollow">http://docs.python.org/3.0/library/functions.html#eval</a></p> <pre><code>def start_interpreter(): while(True): code = input("Python Console &gt;") eval(code) </code></pre> <p>I'm sure, however, that their implementation is much more foolsafe than this.</p>
2
2009-01-14T22:53:16Z
[ "python", "debugging", "interactive" ]
How are debug consoles implemented in Python?
444,509
<p>I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.</p> <p>Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!</p>
10
2009-01-14T20:17:06Z
445,099
<p>Python has a debugger framework in the <a href="http://docs.python.org/library/bdb.html" rel="nofollow">bdb module</a>. I'm not sure if the IDE's you list use it but it's certainly possible to implement a full Python debugger with it.</p>
0
2009-01-14T23:29:13Z
[ "python", "debugging", "interactive" ]
How are debug consoles implemented in Python?
444,509
<p>I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.</p> <p>Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!</p>
10
2009-01-14T20:17:06Z
447,869
<p>Right, I'm ashamed to admit it's actually in the documentation for InteractiveConsole after all. You can make it run in the local context by passing in the result of the locals() function to the InteractiveConsole constructor. I couldn't find a way to close the InteractiveConsole without killing the application, so I've extended it to just close the console when it catches the SystemExit exception. I don't like it, but I haven't yet found a better way.</p> <p>Here's some (fairly trivial) sample code that demonstrates the debug console.</p> <pre><code>import code class EmbeddedConsole(code.InteractiveConsole): def start(self): try: self.interact("Debug console starting...") except: print("Debug console closing...") def print_names(): print(adam) print(bob) adam = "I am Adam" bob = "I am Bob" print_names() console = EmbeddedConsole(locals()) console.start() print_names() </code></pre>
3
2009-01-15T18:25:28Z
[ "python", "debugging", "interactive" ]
How are debug consoles implemented in Python?
444,509
<p>I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.</p> <p>Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated!</p>
10
2009-01-14T20:17:06Z
2,141,143
<p>If you want to experiment with your own Python console then this is a nice start:</p> <pre><code>cmd = None while cmd != 'exit': cmd = raw_input('&gt;&gt;&gt; ') try: exec(cmd) except: print 'exception' </code></pre> <p>But for real work use the InteractiveConsole instead.</p>
0
2010-01-26T17:14:48Z
[ "python", "debugging", "interactive" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
444,610
<p>You can also use the <code>struct</code> module to do this:</p> <pre><code>&gt;&gt;&gt; struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0] 3148270713L </code></pre>
61
2009-01-14T20:52:39Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
444,814
<p>As Greg said, you can use struct if you are dealing with binary values, but if you just have a "hex number" but in byte format you might want to just convert it like:</p> <pre><code>s = 'y\xcc\xa6\xbb' num = int(s.encode('hex'), 16) </code></pre> <p>...this is the same as:</p> <pre><code>num = struct.unpack(">L", s)[0] </code></pre> <p>...except it'll work for any number of bytes.</p>
51
2009-01-14T21:42:52Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
444,855
<pre><code>import array integerValue = array.array("I", 'y\xcc\xa6\xbb')[0] </code></pre> <p>Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.</p>
6
2009-01-14T21:55:37Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
9,634,417
<p>In Python 3.2 and later, use</p> <pre><code>&gt;&gt;&gt; int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big') 2043455163 </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; int.from_bytes(b'y\xcc\xa6\xbb', byteorder='little') 3148270713 </code></pre> <p>according to the endianness of your byte-string.</p> <p>This also works for bytestring-integers of arbitrary length, and for two's-complement signed integers by specifying <code>signed=True</code>. See the <a href="http://docs.python.org/dev/library/stdtypes.html#int.from_bytes">docs for <code>from_bytes</code></a>.</p>
138
2012-03-09T12:56:38Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
22,980,298
<p>I use the following function to convert data between int, hex and bytes.</p> <pre><code>def bytes2int(str): return int(str.encode('hex'), 16) def bytes2hex(str): return '0x'+str.encode('hex') def int2bytes(i): h = int2hex(i) return hex2bytes(h) def int2hex(i): return hex(i) def hex2int(h): if len(h) &gt; 1 and h[0:2] == '0x': h = h[2:] if len(h) % 2: h = "0" + h return int(h, 16) def hex2bytes(h): if len(h) &gt; 1 and h[0:2] == '0x': h = h[2:] if len(h) % 2: h = "0" + h return h.decode('hex') </code></pre> <p>Source: <a href="http://opentechnotes.blogspot.com.au/2014/04/convert-values-to-from-integer-hex.html">http://opentechnotes.blogspot.com.au/2014/04/convert-values-to-from-integer-hex.html</a></p>
5
2014-04-10T06:35:06Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
32,001,227
<p>In Python 2.x, you could use the format specifiers <code>&lt;B</code> for unsigned bytes, and <code>&lt;b</code> for signed bytes with <code>struct.unpack</code>/<code>struct.pack</code>.</p> <p>E.g:</p> <p>Let <code>x</code> = <code>'\xff\x10\x11'</code></p> <p><strike><code>data_ints = [struct.unpack('&lt;B', x)[0] for x in '\xff\x10\x11'] # [255, 16, 17]</code></strike><br> <code>data_ints = struct.unpack('&lt;' + 'B'*len(x), x) # [255, 16, 17]</code></p> <p>And:</p> <p><strike><code>data_bytes = ''.join([struct.pack('&lt;B', x) for x in data_ints]) # '\xff\x10\x11'</code></strike><br> <code>data_bytes = struct.pack('&lt;' + 'B'*len(data_ints), *data_ints) # '\xff\x10\x11'</code> <br><em>That <code>*</code> is required!</em></p> <p>See <a href="https://docs.python.org/2/library/struct.html#format-characters" rel="nofollow"><a href="https://docs.python.org/2/library/struct.html#format-characters" rel="nofollow">https://docs.python.org/2/library/struct.html#format-characters</a></a> for a list of the format specifiers.</p>
2
2015-08-14T02:03:23Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
33,585,619
<p>I was struggling to find a solution for arbitrary length byte sequences that would work under Python 2.x. Finally I wrote this one, it's a bit hacky because it performs a string conversion, but it works.</p> <h1>Function for Python 2.x, arbitrary length</h1> <pre><code>def signedbytes(data): """Convert a bytearray into an integer, considering the first bit as sign. The data must be big-endian.""" negative = data[0] &amp; 0x80 &gt; 0 if negative: inverted = bytearray(~d % 256 for d in data) return -signedbytes(inverted) - 1 encoded = str(data).encode('hex') return int(encoded, 16) </code></pre> <p>This function has two requirements:</p> <ul> <li><p>The input <code>data</code> needs to be a <code>bytearray</code>. You may call the function like this:</p> <pre><code>s = 'y\xcc\xa6\xbb' n = signedbytes(s) </code></pre></li> <li><p>The data needs to be big-endian. In case you have a little-endian value, you should reverse it first:</p> <pre><code>n = signedbytes(s[::-1]) </code></pre></li> </ul> <p>Of course, this should be used only if arbitrary length is needed. Otherwise, stick with more standard ways (e.g. <code>struct</code>).</p>
0
2015-11-07T17:27:15Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
35,634,239
<p>int.from_bytes is the best solution if you are at version >=3.2. The "struct.unpack" solution requires a string so it will not apply to arrays of bytes. Here is another solution:</p> <pre><code>def bytes2int( tb, order='big'): if order == 'big': seq=[0,1,2,3] elif order == 'little': seq=[3,2,1,0] i = 0 for j in seq: i = (i&lt;&lt;8)+tb[j] return i </code></pre> <p>hex( bytes2int( [0x87, 0x65, 0x43, 0x21])) returns '0x87654321'.</p> <p>It handles big and little endianness and is easily modifiable for 8 bytes </p>
1
2016-02-25T17:30:35Z
[ "python", "string", "bytearray" ]
convert a string of bytes into an int (python)
444,591
<p>How can I convert a string of bytes into an int in python? </p> <p>Say like this: <code>'y\xcc\xa6\xbb'</code></p> <p>I came up with a clever/stupid way of doing it:</p> <pre><code>sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) </code></pre> <p>I know there has to be something builtin or in the standard library that does this more simply...</p> <p>This is different from <a href="http://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">converting a string of hex digits</a> for which you can use int(xxx, 16), but instead I want to convert a string of actual byte values.</p> <p>UPDATE:</p> <p>I kind of like James' answer a little better because it doesn't require importing another module, but Greg's method is faster:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; Timer('struct.unpack("&lt;L", "y\xcc\xa6\xbb")[0]', 'import struct').timeit() 0.36242198944091797 &gt;&gt;&gt; Timer("int('y\xcc\xa6\xbb'.encode('hex'), 16)").timeit() 1.1432669162750244 </code></pre> <p>My hacky method:</p> <pre><code>&gt;&gt;&gt; Timer("sum(ord(c) &lt;&lt; (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1]))").timeit() 2.8819329738616943 </code></pre> <p>FURTHER UPDATE:</p> <p>Someone asked in comments what's the problem with importing another module. Well, importing a module isn't necessarily cheap, take a look:</p> <pre><code>&gt;&gt;&gt; Timer("""import struct\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""").timeit() 0.98822188377380371 </code></pre> <p>Including the cost of importing the module negates almost all of the advantage that this method has. I believe that this will only include the expense of importing it once for the entire benchmark run; look what happens when I force it to reload every time:</p> <pre><code>&gt;&gt;&gt; Timer("""reload(struct)\nstruct.unpack("&gt;L", "y\xcc\xa6\xbb")[0]""", 'import struct').timeit() 68.474128007888794 </code></pre> <p>Needless to say, if you're doing a lot of executions of this method per one import than this becomes proportionally less of an issue. It's also probably i/o cost rather than cpu so it may depend on the capacity and load characteristics of the particular machine.</p>
76
2009-01-14T20:46:17Z
39,713,066
<pre><code>&gt;&gt;&gt; reduce(lambda s, x: s*256 + x, bytearray("y\xcc\xa6\xbb")) 2043455163 </code></pre> <p>Test 1: inverse:</p> <pre><code>&gt;&gt;&gt; hex(2043455163) '0x79cca6bb' </code></pre> <p>Test 2: Number of bytes > 8:</p> <pre><code>&gt;&gt;&gt; reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAAA")) 338822822454978555838225329091068225L </code></pre> <p>Test 3: Increment by one:</p> <pre><code>&gt;&gt;&gt; reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAAB")) 338822822454978555838225329091068226L </code></pre> <p>Test 4: Append one byte, say 'A':</p> <pre><code>&gt;&gt;&gt; reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAABA")) 86738642548474510294585684247313465921L </code></pre> <p>Test 5: Divide by 256:</p> <pre><code>&gt;&gt;&gt; reduce(lambda s, x: s*256 + x, bytearray("AAAAAAAAAAAAAABA"))/256 338822822454978555838225329091068226L </code></pre> <p>Result equals the result of Test 4, as expected.</p>
0
2016-09-26T21:58:58Z
[ "python", "string", "bytearray" ]
How to make a wx Toolbar buttons larger?
445,037
<p>I've got a wx.Toolbar and I'd like to make the buttons larger. I've searched and can't seem to find any concrete documentation on how to do this.</p> <p>I'm also wondering how well this will translate across platforms; what will happen to the buttons and icons on OSX?</p>
2
2009-01-14T22:57:53Z
446,014
<p>Doesn't the size of the toolbar adapts itself automatically to the size of the bitmap icons? I think if you want a bigger toolbar, you need bigger bitmaps.</p>
2
2009-01-15T08:28:33Z
[ "python", "user-interface", "wxpython", "wxwidgets", "toolbar" ]
How to make a wx Toolbar buttons larger?
445,037
<p>I've got a wx.Toolbar and I'd like to make the buttons larger. I've searched and can't seem to find any concrete documentation on how to do this.</p> <p>I'm also wondering how well this will translate across platforms; what will happen to the buttons and icons on OSX?</p>
2
2009-01-14T22:57:53Z
450,702
<p>It depends on what you want to change: is it the size of the buttons or the size of the icons ?</p> <p>To change the size of the buttons, use <a href="http://docs.wxwidgets.org/2.6/wx_wxtoolbar.html#wxtoolbarsettoolbitmapsize" rel="nofollow">SetToolBitmapSize</a> (24x24 for instance):</p> <pre><code>toolbar.SetToolBitmapSize((24, 24)) </code></pre> <p>This will only change the size of the buttons, though. If you want to change the size of the icons, simply use bigger ones. The easiest way is to use <a href="http://docs.wxwidgets.org/2.6/wx_wxartprovider.html" rel="nofollow">wx.ArtProvider</a>:</p> <pre><code>wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, (24, 24)) </code></pre> <p>So, summing it up:</p> <pre><code># Define the size of the icons and buttons iconSize = (24, 24) # Set the size of the buttons toolbar.SetToolBitmapSize(iconSize) # Add some button saveIcon = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR, iconSize) toolBar.AddSimpleTool(1, saveIcon, "Save", "Save current file") </code></pre> <p><strong>Remark:</strong> As SetToolBitmapSize changes the size of the buttons, not the size of the icons, you can set the buttons to be larger than the icons. This should leave blank space around the icons.</p>
5
2009-01-16T15:17:29Z
[ "python", "user-interface", "wxpython", "wxwidgets", "toolbar" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,601
<p><a href="http://www.wingware.com/" rel="nofollow">Wing IDE</a> is awesome. They also have a free version.</p>
2
2009-01-15T04:03:37Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,607
<blockquote> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters.</p> </blockquote> <p>Click on the system box (top-left) in the command prompt and click properties. In the layout tab you can set the width and height of the window and the width and height of the screen buffer. I recommend setting the screen buffer height to 9999 so you can scroll back through a long output.</p>
2
2009-01-15T04:07:12Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,618
<p>You can easily widen the Windows console by doing the following:</p> <ul> <li>click the icon for the console window in the upper right</li> <li>select <strong>Properties</strong> from the menu</li> <li>click the <strong>Layout</strong> tab</li> <li>change the <strong>Window Size</strong> > Width to 140</li> </ul> <p>This can also be saved universally by changing the <strong>Defaults</strong> on the menu.</p>
8
2009-01-15T04:14:05Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,626
<p>I edit my Python programs in <a href="http://www.editplus.com/" rel="nofollow">EditPlus</a>. I've configured a user tool that allows me to run my program and have its output appear in a frame below my editor window. My configuration will even let you double click on an exception lines in the output to jump directly to the file and line where the error occurred. You can grab the user tool configuration I use <a href="http://editplus.info/wiki/User_Tools#Python" rel="nofollow">from here on the EditPlus wiki</a>.</p> <p>Perhaps there is similar functionality you can configure that allows you to run your program and display its output in your Emacs editor!?</p>
1
2009-01-15T04:22:29Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,682
<p>For an interactive interpreter, nothing beats <a href="http://ipython.scipy.org/">IPython</a>. It's superb. It's also free and open source. On Windows, you'll want to install the readline library. Instructions for that are on the IPython installation documentation.</p> <p><a href="http://winpdb.org/">Winpdb</a> is my Python debugger of choice. It's free, open source, and cross platform (using wxWidgets for the GUI). I wrote a <a href="http://code.google.com/p/winpdb/wiki/DebuggingTutorial">tutorial on how to use Winpdb</a> to help get people started on using graphical debuggers.</p>
31
2009-01-15T04:49:05Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,767
<p>If you ever graduate to vim, you can just run the following command to start the program you're currently editing in an interactive shell:</p> <pre><code>:!python -i my_script.py </code></pre>
1
2009-01-15T05:31:37Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
445,810
<p>I use eclipse with <a href="http://pydev.sourceforge.net/" rel="nofollow">pydev</a>. Eclipse can be sluggish, but I've become attached to integrated svn/cvs, block indent/unindent and run as unittest features. (Also has F5 run)</p> <p>If your comfortable in emacs though I don't see any reason to make such a major change.</p> <p>I suggest instead that you replace your 'crappy command prompt' with <a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx" rel="nofollow">powershell</a>. It's not as crappy. </p> <p>(As mentioned by Soviut and The Dark - you can increase the buffer width/window size to more than 80 by title-bar>right-click>Properties>Buffer Width/Window Size edit even in crappy cmd)</p>
4
2009-01-15T05:56:23Z
[ "python", "windows", "python-idle" ]
Cleanest way to run/debug python programs in windows
445,595
<p>Python for Windows by default comes with IDLE, which is the barest-bones IDE I've ever encountered. For editing files, I'll stick to emacs, thank you very much.</p> <p>However, I want to run programs in some other shell than the crappy windows command prompt, which can't be widened to more than 80 characters. </p> <p>IDLE lets me run programs in it <em>if</em> I open the file, then hit F5 (to go Run-> Run Module). I would rather like to just "run" the command, rather than going through the rigmarole of closing the emacs file, loading the IDLE file, etc. A scan of google and the IDLE docs doesn't seem to give much help about using IDLE's shell but not it's IDE. </p> <p>Any advice from the stack overflow guys? Ideally I'd either like</p> <ul> <li><p>advice on running programs using IDLE's shell</p></li> <li><p>advice on other ways to run python programs in windows outside of IDLE or "cmd".</p></li> </ul> <p>Thanks,</p> <p>/YGA</p>
18
2009-01-15T04:01:14Z
679,859
<p>I replaced cmd with Cygwin and Poderosa. May be a little overkill though, if the only problem you have with cmd is that it's a pain to resize.</p> <p>Although you use Emacs instead of Vim, so I guess you're into overkill... ;-)</p>
1
2009-03-25T01:03:49Z
[ "python", "windows", "python-idle" ]
GAE - How to live with no joins?
445,827
<h2>Example Problem:</h2> <h3>Entities:</h3> <ul> <li>User contains name and a list of friends (User references)</li> <li>Blog Post contains title, content, date and Writer (User)</li> </ul> <h3>Requirement:</h3> <p>I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep paging back through older entries.</p> <h2>SQL Solution:</h2> <p>So in sql land it would be something like:</p> <pre> select * from blog_post where user_id in (select friend_id from user_friend where user_id = :userId) order by date </pre> <h2>GAE solutions i can think of are:</h2> <ul> <li>Load user, loop through the list of friends and load their latest blog posts. Finally merge all the blog posts to find the latest 10 blog entries</li> <li>In a blog post have a list of all users that have the writer as a friend. This would mean a simple read but would result in quota overload when adding a friend who has lots of blog posts.</li> </ul> <p>I don't believe either of these solutions will scale. </p> <p>Im sure others have hit this problem but I've searched, watched google io videos, read other's code ... What am i missing?</p>
13
2009-01-15T06:07:25Z
446,471
<p>If you look at how the SQL solution you provided will be executed, it will go basically like this:</p> <ol> <li>Fetch a list of friends for the current user</li> <li>For each user in the list, start an index scan over recent posts</li> <li>Merge-join all the scans from step 2, stopping when you've retrieved enough entries</li> </ol> <p>You can carry out exactly the same procedure yourself in App Engine, by using the Query instances as iterators and doing a merge join over them.</p> <p>You're right that this will not scale well to large numbers of friends, but it suffers from exactly the same issues the SQL implementation has, it just doesn't disguise them as well: Fetching the latest 20 (for example) entries costs roughly O(n log n) work, where n is the number of friends.</p>
13
2009-01-15T11:58:10Z
[ "python", "google-app-engine", "join", "gae-datastore" ]
GAE - How to live with no joins?
445,827
<h2>Example Problem:</h2> <h3>Entities:</h3> <ul> <li>User contains name and a list of friends (User references)</li> <li>Blog Post contains title, content, date and Writer (User)</li> </ul> <h3>Requirement:</h3> <p>I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep paging back through older entries.</p> <h2>SQL Solution:</h2> <p>So in sql land it would be something like:</p> <pre> select * from blog_post where user_id in (select friend_id from user_friend where user_id = :userId) order by date </pre> <h2>GAE solutions i can think of are:</h2> <ul> <li>Load user, loop through the list of friends and load their latest blog posts. Finally merge all the blog posts to find the latest 10 blog entries</li> <li>In a blog post have a list of all users that have the writer as a friend. This would mean a simple read but would result in quota overload when adding a friend who has lots of blog posts.</li> </ul> <p>I don't believe either of these solutions will scale. </p> <p>Im sure others have hit this problem but I've searched, watched google io videos, read other's code ... What am i missing?</p>
13
2009-01-15T06:07:25Z
446,477
<p>"Load user, loop through the list of friends and load their latest blog posts."</p> <p>That's all a join is -- nested loops. Some kinds of joins are loops with lookups. Most lookups are just loops; some are hashes.</p> <p>"Finally merge all the blog posts to find the latest 10 blog entries"</p> <p>That's a ORDER BY with a LIMIT. That's what the database is doing for you.</p> <p>I'm not sure what's not scalable about this; it's what a database does anyway.</p>
1
2009-01-15T11:59:10Z
[ "python", "google-app-engine", "join", "gae-datastore" ]
GAE - How to live with no joins?
445,827
<h2>Example Problem:</h2> <h3>Entities:</h3> <ul> <li>User contains name and a list of friends (User references)</li> <li>Blog Post contains title, content, date and Writer (User)</li> </ul> <h3>Requirement:</h3> <p>I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep paging back through older entries.</p> <h2>SQL Solution:</h2> <p>So in sql land it would be something like:</p> <pre> select * from blog_post where user_id in (select friend_id from user_friend where user_id = :userId) order by date </pre> <h2>GAE solutions i can think of are:</h2> <ul> <li>Load user, loop through the list of friends and load their latest blog posts. Finally merge all the blog posts to find the latest 10 blog entries</li> <li>In a blog post have a list of all users that have the writer as a friend. This would mean a simple read but would result in quota overload when adding a friend who has lots of blog posts.</li> </ul> <p>I don't believe either of these solutions will scale. </p> <p>Im sure others have hit this problem but I've searched, watched google io videos, read other's code ... What am i missing?</p>
13
2009-01-15T06:07:25Z
1,043,333
<p>This topic is covered in a Google io talk: <a href="http://code.google.com/events/io/sessions/BuildingScalableComplexApps.html" rel="nofollow">http://code.google.com/events/io/sessions/BuildingScalableComplexApps.html</a></p> <p>Basically the Google team suggest using list properties and what they call relational index entities, an example application can be found here: <a href="http://pubsub-test.appspot.com/" rel="nofollow">http://pubsub-test.appspot.com/</a></p>
7
2009-06-25T11:06:54Z
[ "python", "google-app-engine", "join", "gae-datastore" ]
GAE - How to live with no joins?
445,827
<h2>Example Problem:</h2> <h3>Entities:</h3> <ul> <li>User contains name and a list of friends (User references)</li> <li>Blog Post contains title, content, date and Writer (User)</li> </ul> <h3>Requirement:</h3> <p>I want a page that displays the title and a link to the blog of the last 10 posts by a user's friend. I would also like the ability to keep paging back through older entries.</p> <h2>SQL Solution:</h2> <p>So in sql land it would be something like:</p> <pre> select * from blog_post where user_id in (select friend_id from user_friend where user_id = :userId) order by date </pre> <h2>GAE solutions i can think of are:</h2> <ul> <li>Load user, loop through the list of friends and load their latest blog posts. Finally merge all the blog posts to find the latest 10 blog entries</li> <li>In a blog post have a list of all users that have the writer as a friend. This would mean a simple read but would result in quota overload when adding a friend who has lots of blog posts.</li> </ul> <p>I don't believe either of these solutions will scale. </p> <p>Im sure others have hit this problem but I've searched, watched google io videos, read other's code ... What am i missing?</p>
13
2009-01-15T06:07:25Z
1,786,644
<p>Here is an example in python gleamed from <a href="http://pubsub-test.appspot.com/" rel="nofollow">http://pubsub-test.appspot.com/</a>:</p> <p>Anyone have one for java? Thanks.</p> <pre><code>from google.appengine.ext import webapp from google.appengine.ext import db class Message(db.Model): body = db.TextProperty(required=True) sender = db.StringProperty(required=True) receiver_id = db.ListProperty(int) class SlimMessage(db.Model): body = db.TextProperty(required=True) sender = db.StringProperty(required=True) class MessageIndex(db.Model): receiver_id = db.ListProperty(int) class MainHandler(webapp.RequestHandler): def get(self): receiver_id = int(self.request.get('receiver_id', '1')) key_only = self.request.get('key_only').lower() == 'on' if receiver_id: if key_only: keys = db.GqlQuery( 'SELECT __key__ FROM MessageIndex WHERE receiver_id = :1', receiver_id).fetch(10) messages.extend(db.get([k.parent() for k in keys])) else: messages.extend(Message.gql('WHERE receiver_id = :1', receiver_id).fetch(10)) </code></pre>
0
2009-11-23T22:54:57Z
[ "python", "google-app-engine", "join", "gae-datastore" ]
retrieving XMLHttpRequest parameters in python
445,942
<p>Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are <strong>not</strong> coming from a</p> <pre><code>&lt;form&gt; or &lt;isindex&gt;. </code></pre> <p>How can I retrieve these parameters from within the server-side python script using standard library modules (e.g., cgi)?</p> <p>Thanks very much <p> <strong>EDIT:</strong><br> <em>@codeape</em>: Thanks, but wouldn't that work only for submitted <strong>forms</strong>? In my case, no form is being submitted, just an asynchronous request.<br> Using your script, len(f.keys()) returns 0 if no form is submitted! I can probably recast the request as a form submission, but is there a better way?</p>
3
2009-01-15T07:38:42Z
445,999
<p>You use the cgi.FieldStorage class. Example CGI script:</p> <pre><code>#! /usr/bin/python import cgi from os import environ import cgitb cgitb.enable() print "Content-type: text/plain" print print "REQUEST_METHOD:", environ["REQUEST_METHOD"] print "Values:" f = cgi.FieldStorage() for k in f.keys(): print "%s: %s" % (k, f.getfirst(k)) </code></pre>
5
2009-01-15T08:19:29Z
[ "python", "ajax", "cgi" ]
retrieving XMLHttpRequest parameters in python
445,942
<p>Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are <strong>not</strong> coming from a</p> <pre><code>&lt;form&gt; or &lt;isindex&gt;. </code></pre> <p>How can I retrieve these parameters from within the server-side python script using standard library modules (e.g., cgi)?</p> <p>Thanks very much <p> <strong>EDIT:</strong><br> <em>@codeape</em>: Thanks, but wouldn't that work only for submitted <strong>forms</strong>? In my case, no form is being submitted, just an asynchronous request.<br> Using your script, len(f.keys()) returns 0 if no form is submitted! I can probably recast the request as a form submission, but is there a better way?</p>
3
2009-01-15T07:38:42Z
446,983
<p>codeape already answered on this. Just for the record, please understand that how the HTTP request is emitted is totally orthogonal - what the server get is an HTTP request, period.</p>
0
2009-01-15T14:40:54Z
[ "python", "ajax", "cgi" ]
retrieving XMLHttpRequest parameters in python
445,942
<p>Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are <strong>not</strong> coming from a</p> <pre><code>&lt;form&gt; or &lt;isindex&gt;. </code></pre> <p>How can I retrieve these parameters from within the server-side python script using standard library modules (e.g., cgi)?</p> <p>Thanks very much <p> <strong>EDIT:</strong><br> <em>@codeape</em>: Thanks, but wouldn't that work only for submitted <strong>forms</strong>? In my case, no form is being submitted, just an asynchronous request.<br> Using your script, len(f.keys()) returns 0 if no form is submitted! I can probably recast the request as a form submission, but is there a better way?</p>
3
2009-01-15T07:38:42Z
447,998
<p><em>@codeape</em> , <em>@bruno desthuilliers</em>: <p> Indeed, cgi.FieldStorage() retrieves the parameters. The output I was getting earlier was apparently due to my passing the parameters as a string (JSON.stringify() object) in the body of the request -- rather than as key-value pairs.<br> Thanks</p>
0
2009-01-15T18:59:49Z
[ "python", "ajax", "cgi" ]
Is there an easy way to send SCSI passthrough on OSX using native python
445,980
<p>On Windows I am able to sent SCSI passthrough to devices using win32file.DeviceIOControl(..), on UN*X I can do it using fnctl.ioctl(...).</p> <p>I have been searching for something equivalent in OSX that would allow me to send the IOCTL commands using only native python.</p> <p>I would to send commands to hard drives specifically, not USB devices.</p> <p>Is there anyway to do it without writing a Kernel Extension or any other code using only standard python libraries? </p>
2
2009-01-15T08:06:12Z
535,300
<p>I saw <a href="http://wagerlabs.com/blog/2008/02/04/writing-a-mac-osx-usb-device-driver-that-implements-scsi-pass-through/" rel="nofollow">this blog post</a> recently talking about using SCSI passthrough under OS X. Looks like it isn't as easy as Windows or Unix</p>
1
2009-02-11T03:19:33Z
[ "python", "osx" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
446,116
<p>I've got a couple of ideas, I don't know which one of them is working for me :)</p> <blockquote> <p>Make sure to use a trailing slash, and to have this be different from the MEDIA_URL setting (since the same URL cannot be mapped onto two different sets of files).</p> </blockquote> <p>That's from <a href="http://docs.djangoproject.com/en/dev/ref/settings/#admin-media-prefix" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/settings/#admin-media-prefix</a></p> <p>Secondly, it may be that you're confusing directories on your filesystem with url paths. Try using absolute urls, and then refine them down.</p>
1
2009-01-15T09:15:37Z
[ "python", "css", "django", "django-templates", "media" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
446,138
<p>I just use absolute naming. Unless you're running the site in a deep path (or even if you are), I'd drop the <code>..</code> and go for something like:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/styles.css"&gt; </code></pre>
2
2009-01-15T09:27:23Z
[ "python", "css", "django", "django-templates", "media" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
447,934
<p>I usually make my own Template simple tag because Django isn't giving CSS/JavaScript files. Apache does it so my media url is usually <a href="http://static.mysite.com" rel="nofollow">http://static.mysite.com</a>.</p> <p><strong>yourApp/templatetags/media_url.py:</strong></p> <pre><code>from django.template import Library from yourapp.settings import MEDIA_URL register = Library() @register.simple_tag def media_url(): return MEDIA_URL </code></pre> <p><strong>And in my template file:</strong></p> <pre><code>{% load media_url %} &lt;link href="{{ media_url }}css/main.css" rel="stylesheet" type="text/css"&gt; </code></pre> <p>You could also make <a href="http://stackoverflow.com/questions/433162/can-i-access-constants-in-settings-py-from-templates-in-django#433209">your own context preprocessor</a> to add the media_url variable in every template.</p>
5
2009-01-15T18:40:22Z
[ "python", "css", "django", "django-templates", "media" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
447,991
<p>I just had to figure this out myself.</p> <p>settings.py:</p> <pre><code>MEDIA_ROOT = 'C:/Server/Projects/project_name/static/' MEDIA_URL = '/static/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py:</p> <pre><code>from django.conf import settings ... if settings.DEBUG: urlpatterns += patterns('', (r'^static/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>template file:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/static/css/style.css" /&gt; </code></pre> <p>With the file located here:</p> <pre><code>"C:/Server/Projects/project_name/static/css/style.css" </code></pre>
47
2009-01-15T18:56:51Z
[ "python", "css", "django", "django-templates", "media" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
461,670
<p>Just thought I'd chime in quickly. While all the propositions here work just fine, and I do use Ty's example while developing, once you hit production you might want to opt to serve files via a straight Apache, or whichever else server you're using.</p> <p>What I do is I setup a subdomain once I'm done developing, and replace all links to static media. For instance:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="http://static.mydomain.com/css/style.css" /&gt; </code></pre> <p>The reasons for doing this are two-fold. First, it just seems like it would be slower to have Django handle these requests when it's not needed. Second, since most browsers can actually download files simultaneously from 3 different domains, using a second sub-domain for your static files will actually speed up the download speed of your users.</p>
1
2009-01-20T15:04:57Z
[ "python", "css", "django", "django-templates", "media" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
479,391
<p>Django already has a context process for MEDIA_URL, see <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-media">Django's documentation</a>.</p> <p>It should be availbale by default (unless you've customized CONTEXT_PROCESSORS and forgot to add it) in a RequestContext.</p>
10
2009-01-26T10:49:00Z
[ "python", "css", "django", "django-templates", "media" ]
Django: how do you serve media / stylesheets and link to them within templates
446,026
<p>Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.</p> <p>I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, and hopefully someone can help me to understand where I'm going wrong.</p> <p>Note that I did try to follow the example on the Django project website, however it doesn't mention how to refer to your stylesheets from a template. I've also tried many different variations of the same thing, so my code/settings may be a little off from what's described.</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = 'D:/Dev Tools/django_projects/dso/media' MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/media/' </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/(.*)', admin.site.root), (r'^ovramt/$', 'dso.ovramt.views.index'), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>Within my template:</p> <pre><code>&lt;head&gt; &lt;title&gt; {% block title %} DSO Template {% endblock %} &lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" &gt; &lt;link rel="stylesheet" type="text/css" href="../media/styles.css"&gt; &lt;/head&gt; </code></pre> <p>I assure you, the files (templates/media) are in the correct directory on my file system. If there's any extra information I need to provide, please post a comment.</p> <hr> <p>Edit: </p> <p>One of the problems I was having was the use of a '/' prepending my links. If the forward slash is prepended, the link is opened from the root of the site. If there is no forward slash, the link is opened in the current level. An example:</p> <p>www.example.com/application/ has a link "/app2/ and a link "app3/".<br> app2 will open at www.example.com/app2/ and app3 will open at www.example.com/application/app3/. This was confusing me I think.</p>
41
2009-01-15T08:35:50Z
3,451,369
<p>Another thing to add is that if you have a separate media server on a subdomain/different domain, you can disable cookies for your static media. Saves a little processing and bandwidth.</p>
0
2010-08-10T16:51:58Z
[ "python", "css", "django", "django-templates", "media" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
446,061
<p>You can test using <code>eval</code>:</p> <pre><code>try: eval("1 if True else 2") except SyntaxError: # doesn't have ternary </code></pre> <p>Also, <code>with</code> <em>is</em> available in Python 2.5, just add <code>from __future__ import with_statement </code>.</p> <p>EDIT: to get control early enough, you could split it do different <code>.py</code> files and check compatibility in the main file before importing (e.g. in <code>__init__.py</code> in a package):</p> <pre><code># __init__.py # Check compatibility try: eval("1 if True else 2") except SyntaxError: raise ImportError("requires ternary support") # import from another module from impl import * </code></pre>
88
2009-01-15T08:50:17Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
446,066
<p>I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.</p> <p>eg:</p> <pre><code>try : # Do stuff except : # Features weren't found. # Do stuff for older versions. </code></pre> <p>As long as you're specific in enough in using the try/except blocks, you can cover most of your bases.</p>
1
2009-01-15T08:51:22Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
446,075
<p>Try </p> <pre> import platform platform.python_version() </pre> <p>Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere. </p>
18
2009-01-15T08:55:44Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
446,136
<p>Have a wrapper around your program that does the following.</p> <pre><code>import sys req_version = (2,5) cur_version = sys.version_info if cur_version &gt;= req_version: import myApp myApp.run() else: print "Your Python interpreter is too old. Please consider upgrading." </code></pre> <p>You can also consider using <code>sys.version()</code>, if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.</p> <p>And there might be more elegant ways to do this.</p>
86
2009-01-15T09:26:51Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
446,181
<p>Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:</p> <pre><code>if sys.version_info &lt; (2, 4): from sets import Set as set </code></pre>
7
2009-01-15T09:43:38Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
1,424,136
<p>How about</p> <pre><code>import sys def testPyVer(reqver): if float(sys.version[:3]) &gt;= reqver: return 1 else: return 0 #blah blah blah, more code if testPyVer(3.0) = 1: #do stuff else: #print python requirement, exit statement </code></pre>
-1
2009-09-14T22:00:06Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
2,610,308
<p>The problem is quite simple. You checked if the version was <strong><em>less than</em></strong> 2.4, not less than <strong><em>or equal to</em></strong>. So if the Python version is 2.4, it's not less than 2.4. What you should have had was:</p> <pre><code> if sys.version_info **&lt;=** (2, 4): </code></pre> <p>, not</p> <pre><code> if sys.version_info &lt; (2, 4): </code></pre>
-3
2010-04-09T19:31:02Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
3,132,402
<p>Probably the best way to do do this version comparison is to use the <code>sys.hexversion</code>. This is important because comparing version tuples will not give you the desired result in all python versions.</p> <pre><code>import sys if sys.hexversion &lt; 0x02060000: print "yep!" else: print "oops!" </code></pre>
21
2010-06-28T12:38:59Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
7,396,173
<p>As noted above, syntax errors occur at compile time, not at run time. While Python is an "interpreted language", Python code is not actually directly interpreted; it's compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that's when you're getting your error, not (quite exactly) when your code is running. </p> <p>You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code - and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:</p> <pre><code>import sys if sys.hexversion &lt; 0x02060000: from my_module_2_5 import thisFunc, thatFunc, theOtherFunc else: from my_module import thisFunc, thatFunc, theOtherFunc </code></pre> <p>.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)</p> <p>Another thing that might be worth pointing out (that I'm a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like</p> <pre><code>value = 'yes' if MyVarIsTrue else 'no' </code></pre> <p>..it did support code like</p> <pre><code>value = MyVarIsTrue and 'yes' or 'no' </code></pre> <p>That was the old way of writing ternary expressions. I don't have Python 3 installed yet, but as far as I know, that "old" way still works to this day, so you can decide for yourself whether or not it's worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.</p>
2
2011-09-13T02:27:02Z
[ "python", "version" ]
How can I check for Python version in a program that uses new language features?
446,052
<p>If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?</p> <p>How do I get control early enough to issue an error message and exit?</p> <p>For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.</p> <p>I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:</p> <pre><code>import sys if sys.version_info &lt; (2, 4): raise "must use python 2.5 or greater" else: # syntax error in 2.4, ok in 2.5 x = 1 if True else 2 print x </code></pre> <p>When run under 2.4, I want this result</p> <pre><code>$ ~/bin/python2.4 tern.py must use python 2.5 or greater </code></pre> <p>and not this result:</p> <pre><code>$ ~/bin/python2.4 tern.py File "tern.py", line 5 x = 1 if True else 2 ^ SyntaxError: invalid syntax </code></pre> <p>(Channeling for a coworker.)</p>
194
2009-01-15T08:45:28Z
7,642,536
<p>Although the question is: How do I get control early enough to issue an error message and exit?</p> <p>The question that I answer is: How do I get control early enough to issue an error message before starting the app?</p> <p>I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.</p> <p>I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.</p> <p>Here is the DOS script with version 2.7:</p> <pre><code>@ECHO OFF REM see http://ss64.com/nt/for_f.html FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2&gt;&amp;1"') DO ECHO %%H | find "2.7" &gt; Nul IF NOT ErrorLevel 1 GOTO Python27 ECHO must use python2.7 or greater GOTO EOF :Python27 python.exe tern.py GOTO EOF :EOF </code></pre> <p>This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.</p> <p>The "FOR /F" line is the key. FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&amp;1"') DO ECHO %%H | find "2.7" > Nul</p> <p>For multiple python version check check out url: <a href="http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17">http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17</a></p> <p>And my hack version:</p> <p>[MS script; Python version check prelaunch of Python module] <a href="http://pastebin.com/aAuJ91FQ">http://pastebin.com/aAuJ91FQ</a></p>
7
2011-10-04T01:52:20Z
[ "python", "version" ]