title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
1,534,532
<pre><code>print "var" print "something_else" </code></pre> <p>Or did you mean something_else?</p>
0
2009-10-07T22:11:58Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
1,534,543
<p>You somehow have to refer to the variable you want to print the name of. So it would look like:</p> <pre><code>print varname(something_else) </code></pre> <p>There is no such function, but if there were it would be kind of pointless. You have to type out <code>something_else</code>, so you can as well just type quotes to the left and right of it to print the name as a string:</p> <pre><code>print "something_else" </code></pre>
3
2009-10-07T22:13:17Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
1,534,553
<p>This is not possible.</p> <p>In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.</p> <p>Consider this example:</p> <pre><code>foo = 1 bar = 1 baz = 1 </code></pre> <p>Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.</p> <p>In Python, a name is a way to access an object, so there is no way to work with names directly. There might be some clever way to hack the Python bytecodes or something to get the value of the name, but that is at best a parlor trick.</p> <p>If you know you want <code>print foo</code> to print <code>"foo"</code>, you might as well just execute <code>print "foo"</code> in the first place.</p> <p>EDIT: I have changed the wording slightly to make this more clear. Also, here is an even better example:</p> <pre><code>foo = 1 bar = foo baz = foo </code></pre> <p>In practice, Python reuses the same object for integers with common values like 0 or 1, so the first example should bind the same object to all three names. But this example is crystal clear: the same object is bound to foo, bar, and baz.</p>
7
2009-10-07T22:15:55Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
1,534,618
<p>Technically the information is available to you, but as others have asked, how would you make use of it in a sensible way?</p> <pre><code>&gt;&gt;&gt; x = 52 &gt;&gt;&gt; globals() {'__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__name__': '__main__', 'x': 52, '__doc__': None, '__package__': None} </code></pre> <p>This shows that the variable name is present as a string in the globals() dictionary.</p> <pre><code>&gt;&gt;&gt; globals().keys()[2] 'x' </code></pre> <p>In this case it happens to be the third key, but there's no reliable way to know where a given variable name will end up</p> <pre><code>&gt;&gt;&gt; for k in globals().keys(): ... if not k.startswith("_"): ... print k ... x &gt;&gt;&gt; </code></pre> <p>You could filter out system variables like this, but you're still going to get all of your own items. Just running that code above created another variable "k" that changed the position of "x" in the dict.</p> <p>But maybe this is a useful start for you. If you tell us what you want this capability for, more helpful information could possibly be given.</p>
7
2009-10-07T22:37:22Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
1,535,029
<p>What are you trying to achieve? There is absolutely no reason to ever do what you describe, and there is likely a much better solution to the problem you're trying to solve..</p> <p>The most obvious alternative to what you request is a dictionary. For example:</p> <pre><code>&gt;&gt;&gt; my_data = {'var': 'something'} &gt;&gt;&gt; my_data['something_else'] = 'something' &gt;&gt;&gt; print my_data.keys() ['var', 'something_else'] &gt;&gt;&gt; print my_data['var'] something </code></pre> <p>Mostly as a.. challenge, I implemented your desired output. Do not use this code, please!</p> <pre><code>#!/usr/bin/env python2.6 class NewLocals: """Please don't ever use this code..""" def __init__(self, initial_locals): self.prev_locals = list(initial_locals.keys()) def show_new(self, new_locals): output = ", ".join(list(set(new_locals) - set(self.prev_locals))) self.prev_locals = list(new_locals.keys()) return output # Set up eww = None eww = NewLocals(locals()) # "Working" requested code var = {} print eww.show_new(locals()) # Outputs: var something_else = 3 print eww.show_new(locals()) # Outputs: something_else # Further testing another_variable = 4 and_a_final_one = 5 print eww.show_new(locals()) # Outputs: another_variable, and_a_final_one </code></pre>
3
2009-10-08T00:51:42Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
3,683,258
<p>There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.</p> <p>This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.</p> <p>What would be needed, is the reverse of the <code>eval()</code> function:</p> <pre><code>get_indentifier_name_missing_function() </code></pre> <p>which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.</p> <hr> <p>Consider the following current state of affairs:</p> <pre><code>random_function(argument_data) </code></pre> <p>If one is passing an identifier name ('function','variable','dictionary',etc) <code>argument_data</code> to a <code>random_function()</code> (another identifier name), one actually passes an identifier (e.g.: <code>&lt;argument_data object at 0xb1ce10&gt;</code>) to another identifier (e.g.: <code>&lt;function random_function at 0xafff78&gt;</code>):</p> <pre><code>&lt;function random_function at 0xafff78&gt;(&lt;argument_data object at 0xb1ce10&gt;) </code></pre> <p>From my understanding, only the memory address is passed to the function:</p> <pre><code>&lt;function at 0xafff78&gt;(&lt;object at 0xb1ce10&gt;) </code></pre> <p>Therefore, one would need to pass a string as an argument to <code>random_function()</code> in order for that function to have the argument's identifier name:</p> <pre><code>random_function('argument_data') </code></pre> <p>Inside the random_function()</p> <pre><code>def random_function(first_argument): </code></pre> <p>, one would use the already supplied string <code>'argument_data'</code> to:</p> <ol> <li>serve as an 'identifier name' (to display, log, string split/concat, whatever)</li> <li><p>feed the <code>eval()</code> function in order to get a reference to the actual identifier, and therefore, a reference to the real data:</p> <pre><code>print("Currently working on", first_argument) some_internal_var = eval(first_argument) print("here comes the data: " + str(some_internal_var)) </code></pre></li> </ol> <p>Unfortunately, this doesn't work in all cases. It only works if the <code>random_function()</code> can resolve the <code>'argument_data'</code> string to an actual identifier. I.e. If <code>argument_data</code> identifier name is available in the <code>random_function()</code>'s namespace.</p> <p>This isn't always the case:</p> <pre><code># main1.py import some_module1 argument_data = 'my data' some_module1.random_function('argument_data') # some_module1.py def random_function(first_argument): print("Currently working on", first_argument) some_internal_var = eval(first_argument) print("here comes the data: " + str(some_internal_var)) ###### </code></pre> <p>Expected results would be:</p> <pre><code>Currently working on: argument_data here comes the data: my data </code></pre> <p>Because <code>argument_data</code> identifier name is not available in the <code>random_function()</code>'s namespace, this would yield instead:</p> <pre><code>Currently working on argument_data Traceback (most recent call last): File "~/main1.py", line 6, in &lt;module&gt; some_module1.random_function('argument_data') File "~/some_module1.py", line 4, in random_function some_internal_var = eval(first_argument) File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'argument_data' is not defined </code></pre> <hr> <p>Now, consider the hypotetical usage of a <code>get_indentifier_name_missing_function()</code> which would behave as described above.</p> <p>Here's a dummy Python 3.0 code: .</p> <pre><code># main2.py import some_module2 some_dictionary_1 = { 'definition_1':'text_1', 'definition_2':'text_2', 'etc':'etc.' } some_other_dictionary_2 = { 'key_3':'value_3', 'key_4':'value_4', 'etc':'etc.' } # # more such stuff # some_other_dictionary_n = { 'random_n':'random_n', 'etc':'etc.' } for each_one_of_my_dictionaries in ( some_dictionary_1, some_other_dictionary_2, ..., some_other_dictionary_n ): some_module2.some_function(each_one_of_my_dictionaries) # some_module2.py def some_function(a_dictionary_object): for _key, _value in a_dictionary_object.items(): print( get_indentifier_name_missing_function(a_dictionary_object) + " " + str(_key) + " = " + str(_value) ) ###### </code></pre> <p>Expected results would be:</p> <pre><code>some_dictionary_1 definition_1 = text_1 some_dictionary_1 definition_2 = text_2 some_dictionary_1 etc = etc. some_other_dictionary_2 key_3 = value_3 some_other_dictionary_2 key_4 = value_4 some_other_dictionary_2 etc = etc. ...... ...... ...... some_other_dictionary_n random_n = random_n some_other_dictionary_n etc = etc. </code></pre> <p>Unfortunately, <code>get_indentifier_name_missing_function()</code> would not see the 'original' identifier names (<code>some_dictionary_</code>,<code>some_other_dictionary_2</code>,<code>some_other_dictionary_n</code>). It would only see the <code>a_dictionary_object</code> identifier name.</p> <p>Therefore the real result would rather be:</p> <pre><code>a_dictionary_object definition_1 = text_1 a_dictionary_object definition_2 = text_2 a_dictionary_object etc = etc. a_dictionary_object key_3 = value_3 a_dictionary_object key_4 = value_4 a_dictionary_object etc = etc. ...... ...... ...... a_dictionary_object random_n = random_n a_dictionary_object etc = etc. </code></pre> <p>So, the reverse of the <code>eval()</code> function won't be that useful in this case.</p> <hr> <p>Currently, one would need to do this:</p> <pre><code># main2.py same as above, except: for each_one_of_my_dictionaries_names in ( 'some_dictionary_1', 'some_other_dictionary_2', '...', 'some_other_dictionary_n' ): some_module2.some_function( { each_one_of_my_dictionaries_names : eval(each_one_of_my_dictionaries_names) } ) # some_module2.py def some_function(a_dictionary_name_object_container): for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items(): for _key, _value in _dictionary_object.items(): print( str(_dictionary_name) + " " + str(_key) + " = " + str(_value) ) ###### </code></pre> <hr> <h2>In conclusion:</h2> <ul> <li>Python passes only memory addresses as arguments to functions.</li> <li>Strings representing the name of an identifier, can only be referenced back to the actual identifier by the <code>eval()</code> function if the name identifier is available in the current namespace.</li> <li>A hypothetical reverse of the <code>eval()</code> function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.</li> <li>Currently one needs to pass to a function: <ol> <li>the string representing the identifier name</li> <li>the actual identifier (memory address)</li> </ol></li> </ul> <p>This can be achieved by passing both the <code>'string'</code> and <code>eval('string')</code> to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the <code>eval()</code> function which may easily lead to unsecured code. Care must be taken to not feed the <code>eval()</code> function with just about anything, especially unfiltered external-input data.</p>
27
2010-09-10T08:46:57Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
5,172,892
<p>Does Django not do this when generating field names?</p> <p><a href="http://docs.djangoproject.com/en/dev//topics/db/models/#verbose-field-names" rel="nofollow">http://docs.djangoproject.com/en/dev//topics/db/models/#verbose-field-names</a></p> <p>Seems reasonable to me.</p>
2
2011-03-02T20:15:40Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
6,504,497
<p>This will work for simnple data types (str, int, float, list etc.)</p> <pre> >>> def my_print(var_str) : print var_str+':', globals()[var_str] >>> a = 5 >>> b = ['hello', ',world!'] >>> my_print('a') a: 5 >>> my_print('b') b: ['hello', ',world!'] </pre>
0
2011-06-28T09:40:31Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
6,797,755
<p>I searched for this question because I wanted a Python program to print assignment statements for some of the variables in the program. For example, it might print "foo = 3, bar = 21, baz = 432". The print function would need the variable names in string form. I could have provided my code with the strings "foo","bar", and "baz", but that felt like repeating myself. After reading the previous answers, I developed the solution below.</p> <p>The globals() function behaves like a dict with variable names (in the form of strings) as keys. I wanted to retrieve from globals() the key corresponding to the value of each variable. The method globals().items() returns a list of tuples; in each tuple the first item is the variable name (as a string) and the second is the variable value. My variablename() function searches through that list to find the variable name(s) that corresponds to the value of the variable whose name I need in string form.</p> <p>The function itertools.ifilter() does the search by testing each tuple in the globals().items() list with the function <code>lambda x: var is globals()[x[0]]</code>. In that function x is the tuple being tested; x[0] is the variable name (as a string) and x[1] is the value. The lambda function tests whether the value of the tested variable is the same as the value of the variable passed to variablename(). In fact, by using the <code>is</code> operator, the lambda function tests whether the name of the tested variable is bound to the exact same object as the variable passed to variablename(). If so, the tuple passes the test and is returned by ifilter().</p> <p>The itertools.ifilter() function actually returns an iterator which doesn't return any results until it is called properly. To get it called properly, I put it inside a list comprehension <code>[tpl[0] for tpl ... globals().items())]</code>. The list comprehension saves only the variable name <code>tpl[0]</code>, ignoring the variable value. The list that is created contains one or more names (as strings) that are bound to the value of the variable passed to variablename().</p> <p>In the uses of variablename() shown below, the desired string is returned as an element in a list. In many cases, it will be the only item in the list. If another variable name is assigned the same value, however, the list will be longer.</p> <pre><code>&gt;&gt;&gt; def variablename(var): ... import itertools ... return [tpl[0] for tpl in ... itertools.ifilter(lambda x: var is x[1], globals().items())] ... &gt;&gt;&gt; var = {} &gt;&gt;&gt; variablename(var) ['var'] &gt;&gt;&gt; something_else = 3 &gt;&gt;&gt; variablename(something_else) ['something_else'] &gt;&gt;&gt; yet_another = 3 &gt;&gt;&gt; variablename(something_else) ['yet_another', 'something_else'] </code></pre>
4
2011-07-23T01:56:15Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
13,279,103
<p>I think this is a cool solution and I suppose the best you can get. But do you see any way to handle the ambigious results, your function may return? As <a href="http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers">Python &quot;is&quot; operator behaves unexpectedly with integers</a> shows, low integers and strings of the same value get cached by python so that your variablename-function might priovide ambigous results with a high probability. In my case, I would like to create a decorator, that adds a new variable to a class by the varialbename i pass it:</p> <pre><code>def inject(klass, dependency): klass.__dict__["__"+variablename(dependency)]=dependency </code></pre> <p>But if your method returns ambigous results, how can I know the name of the variable I added?</p> <pre><code>var any_var="myvarcontent" var myvar="myvarcontent" @inject(myvar) class myclasss(): def myclass_method(self): print self.__myvar #I can not be sure, that this variable will be set... </code></pre> <p>Maybe if I will also check the local list I could at least remove the "dependency"-Variable from the list, but this will not be a reliable result.</p>
2
2012-11-07T22:07:19Z
[ "python", "string", "variables" ]
Convert Variable Name to String?
1,534,504
<p>I would like to convert a python variable name into the string equivalent as shown. Any ideas how?</p> <pre><code>var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' </code></pre>
29
2009-10-07T22:06:13Z
15,361,037
<p>as long as it's a variable and not a second class, this here works for me:</p> <pre><code>def print_var_name(variable): for name in globals(): if eval(name) == variable: print name foo = 123 print_var_name(foo) &gt;&gt;&gt;foo </code></pre> <p>this happens for class members:</p> <pre><code>class xyz: def __init__(self): pass member = xyz() print_var_name(member) &gt;&gt;&gt;member </code></pre> <p>ans this for classes (as example):</p> <pre><code>abc = xyz print_var_name(abc) &gt;&gt;&gt;abc &gt;&gt;&gt;xyz </code></pre> <p>So for classes it gives you the name AND the properteries</p>
2
2013-03-12T12:20:24Z
[ "python", "string", "variables" ]
Can I sort text by its numeric value in Python?
1,534,542
<p>I have dict in Python with keys of the following form:</p> <pre><code>mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, '11.1' : 243, '12.0' : 3, '12.1.0': 1, '12.1.1': 2, } </code></pre> <p>Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have <code>10</code> following <code>1</code> and <code>20</code> following <code>2</code>.</p> <p>How can I sort the indices correctly?</p> <p><strong>Note:</strong> What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.</p>
10
2009-10-07T22:13:17Z
1,534,568
<p>You can sort the keys the way that you want, by splitting them on '.' and then converting each of the components into an integer, like this:</p> <pre><code>sorted(mydict.keys(), key=lambda a:map(int,a.split('.'))) </code></pre> <p>which returns this:</p> <pre><code>['0', '1', '2.0', '2.1', '3', '4.0.0', '4.0.1', '5', '10', '11.0', '11.1', '12.0', '12.1.0', '12.1.1'] </code></pre> <p>You can iterate over that list of keys, and pull the values out of your dictionary as needed.</p> <p>You could also sort the result of mydict.items(), very similarly:</p> <pre><code>sorted(mydict.items(), key=lambda a:map(int,a[0].split('.'))) </code></pre> <p>This gives you a sorted list of (key, value) pairs, like this:</p> <pre><code>[('0', 10), ('1', 23), ('2.0', 321), ('2.1', 3231), ('3', 3), # ... ('12.1.1', 2)] </code></pre>
18
2009-10-07T22:21:10Z
[ "python", "string", "sorting" ]
Can I sort text by its numeric value in Python?
1,534,542
<p>I have dict in Python with keys of the following form:</p> <pre><code>mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, '11.1' : 243, '12.0' : 3, '12.1.0': 1, '12.1.1': 2, } </code></pre> <p>Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have <code>10</code> following <code>1</code> and <code>20</code> following <code>2</code>.</p> <p>How can I sort the indices correctly?</p> <p><strong>Note:</strong> What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.</p>
10
2009-10-07T22:13:17Z
1,534,569
<p>Python's sorting functions can take a custom compare function, so you just need to define a function that compares keys the way you like:</p> <pre><code>def version_cmp(a, b): '''These keys just look like version numbers to me....''' ai = map(int, a.split('.')) bi = map(int, b.split('.')) return cmp(ai, bi) for k in sorted(mydict.keys(), version_cmp): print k, mydict[k] </code></pre> <p>In this case you should better to use the <code>key</code> parameter to <code>sorted()</code>, though. See <a href="http://stackoverflow.com/questions/1534542/can-i-sort-text-by-its-numeric-value-in-python#1534568">Ian Clelland</a>'s answer for an example for that.</p>
2
2009-10-07T22:21:10Z
[ "python", "string", "sorting" ]
Can I sort text by its numeric value in Python?
1,534,542
<p>I have dict in Python with keys of the following form:</p> <pre><code>mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, '11.1' : 243, '12.0' : 3, '12.1.0': 1, '12.1.1': 2, } </code></pre> <p>Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have <code>10</code> following <code>1</code> and <code>20</code> following <code>2</code>.</p> <p>How can I sort the indices correctly?</p> <p><strong>Note:</strong> What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.</p>
10
2009-10-07T22:13:17Z
1,534,571
<p>I would do a search on <a href="http://stackoverflow.com/search?q=sorting+a+python+dictionary">"sorting a python dictionary"</a> and take a look at the answers. I would give <a href="http://www.python.org/dev/peps/pep-0265/" rel="nofollow">PEP-265</a> a read as well. The <a href="http://docs.python.org/library/functions.html?highlight=sorted#sorted" rel="nofollow"><code>sorted()</code></a> function is what you are looking for.</p>
0
2009-10-07T22:21:30Z
[ "python", "string", "sorting" ]
Can I sort text by its numeric value in Python?
1,534,542
<p>I have dict in Python with keys of the following form:</p> <pre><code>mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, '11.1' : 243, '12.0' : 3, '12.1.0': 1, '12.1.1': 2, } </code></pre> <p>Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have <code>10</code> following <code>1</code> and <code>20</code> following <code>2</code>.</p> <p>How can I sort the indices correctly?</p> <p><strong>Note:</strong> What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.</p>
10
2009-10-07T22:13:17Z
1,534,816
<p>As an addendum to <a href="http://stackoverflow.com/questions/1534542/can-i-sort-text-by-its-numeric-value-in-python#1534568" title="Ian Clelland's">Ian Clelland's</a> answer, the <code>map()</code> call can be replaced with a list comprehension... if you prefer that style. It <em>may</em> also be more efficient (though negligibly in this case I suspect).</p> <p><code>sorted(mydict.keys(), key=lambda a: [int(i) for i in a.split('.')])</code></p>
2
2009-10-07T23:42:48Z
[ "python", "string", "sorting" ]
Can I sort text by its numeric value in Python?
1,534,542
<p>I have dict in Python with keys of the following form:</p> <pre><code>mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, '11.1' : 243, '12.0' : 3, '12.1.0': 1, '12.1.1': 2, } </code></pre> <p>Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have <code>10</code> following <code>1</code> and <code>20</code> following <code>2</code>.</p> <p>How can I sort the indices correctly?</p> <p><strong>Note:</strong> What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.</p>
10
2009-10-07T22:13:17Z
3,590,671
<p>For fun &amp; usefulness (for googling ppl, mostly):</p> <pre><code>f = lambda i: [int(j) if re.match(r"[0-9]+", j) else j for j in re.findall(r"([0-9]+|[^0-9]+)", i)] cmpg = lambda x, y: cmp(f(x), f(y)) </code></pre> <p>use as <code>sorted(list, cmp=cmpg)</code>. Additionally, regexes might be pre-compiled (rarely necessary though, actually, with re module's caching). And, it may be (easily) modified, for example, to include negative values (add <code>-?</code> to num regex, probably) and/or to use float values.</p> <p>It might be not very efficient, but even with that it's quite useful.</p> <p>And, uhm, it can be used as key= for sorted() too.</p>
1
2010-08-28T12:02:45Z
[ "python", "string", "sorting" ]
Can I sort text by its numeric value in Python?
1,534,542
<p>I have dict in Python with keys of the following form:</p> <pre><code>mydict = {'0' : 10, '1' : 23, '2.0' : 321, '2.1' : 3231, '3' : 3, '4.0.0' : 1, '4.0.1' : 10, '5' : 11, # ... etc '10' : 32, '11.0' : 3, '11.1' : 243, '12.0' : 3, '12.1.0': 1, '12.1.1': 2, } </code></pre> <p>Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I'll have <code>10</code> following <code>1</code> and <code>20</code> following <code>2</code>.</p> <p>How can I sort the indices correctly?</p> <p><strong>Note:</strong> What I really want to do is print out the dict sorted by index. If there's a better way to do it than sorting it somehow that's fine with me.</p>
10
2009-10-07T22:13:17Z
5,039,120
<p>There is a nice sorting HOWTO on the python web site: <a href="http://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">http://wiki.python.org/moin/HowTo/Sorting</a> . It makes a good introduction to sorting, and discusses different techniques to adapt the sorting result to your needs.</p>
0
2011-02-18T08:33:56Z
[ "python", "string", "sorting" ]
Creating a program to be broadcasted by avahi
1,534,655
<p>I'm trying to write a program that outputs data that can be served over a network with avahi. The documentation I've looked at seems to say I have to register the service with dbus and then connect it to avahi, but the documentation to do this is pretty sparse. Does anyone know of good documentation for it? I've been looking at these:</p> <p>python-dbus: <a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-objects" rel="nofollow">http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-objects</a></p> <p>python-avahi: <a href="http://www.amk.ca/diary/2007/04/rough%5Fnotes%5Fpython%5Fand%5Fdbus.html" rel="nofollow">http://www.amk.ca/diary/2007/04/rough%5Fnotes%5Fpython%5Fand%5Fdbus.html</a></p> <p>I'm really unfamiliar with how avahi works at all, so any pointers would be helpful.</p>
3
2009-10-07T22:52:11Z
1,561,594
<p>Avahi is "just" a Client implementation of <a href="http://en.wikipedia.org/wiki/Zero%5Fconfiguration%5Fnetworking" rel="nofollow">ZeroConfig</a> which basically is a "Multicast based DNS" protocol. You can use Avahi to publish the availability of your "data" through end-points. The actual data must be retrieved through some other means but you would normally register an end-point that can be "invoked" through a method of your liking.</p>
0
2009-10-13T17:04:36Z
[ "python", "dbus", "avahi" ]
Creating a program to be broadcasted by avahi
1,534,655
<p>I'm trying to write a program that outputs data that can be served over a network with avahi. The documentation I've looked at seems to say I have to register the service with dbus and then connect it to avahi, but the documentation to do this is pretty sparse. Does anyone know of good documentation for it? I've been looking at these:</p> <p>python-dbus: <a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-objects" rel="nofollow">http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-objects</a></p> <p>python-avahi: <a href="http://www.amk.ca/diary/2007/04/rough%5Fnotes%5Fpython%5Fand%5Fdbus.html" rel="nofollow">http://www.amk.ca/diary/2007/04/rough%5Fnotes%5Fpython%5Fand%5Fdbus.html</a></p> <p>I'm really unfamiliar with how avahi works at all, so any pointers would be helpful.</p>
3
2009-10-07T22:52:11Z
1,731,577
<p>If your program is written in Java, then you can use avahi4j which provides an easy to use API to register (and browse) Bonjour services on your local network. <a href="http://avahi4j.googlecode.com" rel="nofollow">http://avahi4j.googlecode.com</a></p>
-2
2009-11-13T20:07:32Z
[ "python", "dbus", "avahi" ]
Creating a program to be broadcasted by avahi
1,534,655
<p>I'm trying to write a program that outputs data that can be served over a network with avahi. The documentation I've looked at seems to say I have to register the service with dbus and then connect it to avahi, but the documentation to do this is pretty sparse. Does anyone know of good documentation for it? I've been looking at these:</p> <p>python-dbus: <a href="http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-objects" rel="nofollow">http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#exporting-objects</a></p> <p>python-avahi: <a href="http://www.amk.ca/diary/2007/04/rough%5Fnotes%5Fpython%5Fand%5Fdbus.html" rel="nofollow">http://www.amk.ca/diary/2007/04/rough%5Fnotes%5Fpython%5Fand%5Fdbus.html</a></p> <p>I'm really unfamiliar with how avahi works at all, so any pointers would be helpful.</p>
3
2009-10-07T22:52:11Z
18,104,922
<p>I realise this answer is pretty late, considering your question was asked four years ago. However, it might help others.</p> <p>The following announces a service using avahi/dbus:</p> <pre><code>import avahi import dbus from time import sleep class ServiceAnnouncer: def __init__(self, name, service, port, txt): bus = dbus.SystemBus() server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP) self._service_name = name index = 1 while True: try: group.AddService(avahi.IF_UNSPEC, avahi.PROTO_INET, 0, self._service_name, service, '', '', port, avahi.string_array_to_txt_array(txt)) except dbus.DBusException: # name collision -&gt; rename index += 1 self._service_name = '%s #%s' % (name, str(index)) else: break group.Commit() def get_service_name(self): return self._service_name if __name__ == '__main__': announcer = ServiceAnnouncer('Test Service', '_test._tcp', 12345, ['foo=bar', '42=true']) print announcer.get_service_name() sleep(42) </code></pre> <p>Using avahi-browse to verify it is indeed published:</p> <pre><code>micke@els-mifr-03:~$ avahi-browse -a -v -t -r Server version: avahi 0.6.30; Host name: els-mifr-03.local E Ifce Prot Name Type Domain + eth0 IPv4 Test Service _test._tcp local = eth0 IPv4 Test Service _test._tcp local hostname = [els-mifr-03.local] address = [10.9.0.153] port = [12345] txt = ["42=true" "foo=bar"] </code></pre>
9
2013-08-07T13:37:46Z
[ "python", "dbus", "avahi" ]
Attribute as dict of lists using middleman table with SQLAlchemy
1,534,673
<p>My question is about SQLAlchemy but I'm having troubles explaining it in words so I figured I explain it with a simple example of what I'm trying to achieve:</p> <pre><code>parent = Table('parent', metadata, Column('parent_id', Integer, primary_key=True), Column('name', Unicode), ) parent_child = Table('parent_child', metadata, Column('parent_id', Integer, primary_key=True), Column('child_id', Integer, primary_key=True), Column('number', Integer), ForeignKeyConstraint(['parent_id'], ['parent.parent_id']), ForeignKeyConstraint(['child_id'], ['child.child_id']), ) child = Table('child', metadata, Column('child_id', Integer, primary_key=True), Column('name', Unicode), ) class Parent(object): pass class ParentChild(object): pass class Child(object): pass &gt;&gt;&gt; p = Parent(name=u'A') &gt;&gt;&gt; print p.children {} &gt;&gt;&gt; p.children[0] = Child(name=u'Child A') &gt;&gt;&gt; p.children[10] = Child(name=u'Child B') &gt;&gt;&gt; p.children[10] = Child(name=u'Child C') </code></pre> <p>This code would create 3 rows in parent_child table, column number would be 0 for the first row, and 10 for the second and third row.</p> <pre><code>&gt;&gt;&gt; print p.children {0: [&lt;Child A&gt;], 10: [&lt;Child B&gt;, &lt;Child C&gt;]} &gt;&gt;&gt; print p.children[10][0] &lt;Child B&gt; </code></pre> <p>(I left out all SQLAlchemy session/engine code in the example to make it as clean as possible)</p> <p>I did a try using´</p> <pre><code>collection_class=attribute_mapped_collection('number') </code></pre> <p>on a relation between Parent and ParentChild, but it only gave me one child for each number. Not a dict with lists in it. Any help appreciated!</p> <h3>UPDATED!</h3> <p>Thanks to Denis Otkidach I now has this code, but it still doesn't work.</p> <pre><code>def _create_children(number, child): return ParentChild(parent=None, child=child, number=number) class Parent(object): children = association_proxy('_children', 'child', creator=_create_children) class MyMappedCollection(MappedCollection): def __init__(self): keyfunc = lambda attr_name: operator.attrgetter('number') MappedCollection.__init__(self, keyfunc=keyfunc) @collection.appender @collection.internally_instrumented def set(self, value, _sa_initiator=None): key = self.keyfunc(value) try: self.__getitem__(key).append(value) except KeyError: self.__setitem__(key, [value]) mapper(Parent, parent, properties={ '_children': relation(ParentChild, collection_class=MyMappedCollection), }) </code></pre> <p>To insert an Child seems to work</p> <pre><code>p.children[100] = Child(...) </code></pre> <p>But when I try to print children like this:</p> <pre><code>print p.children </code></pre> <p>I get this error:</p> <pre><code>sqlalchemy.orm.exc.UnmappedInstanceError: Class '__builtin__.list' is not mapped </code></pre>
3
2009-10-07T22:55:49Z
1,543,559
<p>You have to define your own collection class. There are only 3 methods to implement: appender, remover, and converter. See <code>sqlalchemy.orm.collections.MappedCollection</code> as an example.</p> <p><strong>Update:</strong> Here is quick-n-dirty implementation according to your requirements:</p> <pre><code>from sqlalchemy import * from sqlalchemy.orm import mapper, relation, sessionmaker from sqlalchemy.orm.collections import collection metadata = MetaData() parent = Table('parent', metadata, Column('parent_id', Integer, primary_key=True), Column('name', Unicode), ) child = Table('child', metadata, Column('child_id', Integer, primary_key=True), Column('name', Unicode), ) parent_child = Table('parent_child', metadata, Column('parent_id', Integer, ForeignKey(parent.c.parent_id)), Column('child_id', Integer, ForeignKey(child.c.child_id)), Column('number', Integer), PrimaryKeyConstraint('parent_id', 'child_id'), ) class ParentChild(object): def __init__(self, child, number): self.child = child self.number = number class Parent(object): pass class Child(object): pass class MyMappedCollection(object): def __init__(self, data=None): self._data = data or {} @collection.appender def _append(self, parent_child): l = self._data.setdefault(parent_child.number, []) l.append(parent_child) def __setitem__(self, number, child): self._append(ParentChild(number=number, child=child)) def __getitem__(self, number): return tuple(pc.child for pc in self._data[number]) @collection.remover def _remove(self, parent_child): self._data[parent_child.number].remove(parent_child) @collection.iterator def _iterator(self): for pcs in self._data.itervalues(): for pc in pcs: yield pc def __repr__(self): return '%s(%r)' % (type(self).__name__, self._data) mapper(Parent, parent, properties={ 'children': relation(ParentChild, collection_class=MyMappedCollection), }) mapper(Child, child) mapper(ParentChild, parent_child, properties={ 'parent': relation(Parent), 'child': relation(Child), }) engine = create_engine('sqlite://') db = sessionmaker(bind=engine)() metadata.create_all(bind=engine) p = Parent() c1 = Child() c2 = Child() c3 = Child() p.children[1] = c1 p.children[1] = c2 p.children[2] = c3 db.add(p) db.commit() p_id = p.parent_id db.expunge_all() p = db.query(Parent).get(p_id) print p.children[1] print p.children[2] </code></pre>
2
2009-10-09T12:50:09Z
[ "python", "sqlalchemy" ]
Calling a RPC function in a running Windows service (process) using Python
1,534,686
<p>I have Windows service (acts as a server) that I want to test using Python scripts. This service is written in C++ and exposes several RPC functions that other services consume. I want to mock those other services using my Python program and call those RPC functions from the script. This is the first stage. The second stage happens when the server service responds to its caller service by another RPC call. How can this be done in Python?</p> <p>If Python (or any of its extensions) can't call/receive the RPCs, can this be done if I change the main server service code and added whatever code is necessary, which will end up calling the same functionality the RPCs used to execute but will be callable from Python?</p> <p>Note: The server service implements the RPC functions using raw Windows RPC implemented with IDL files. Other services, which are written in C++ too, interested in consuming those RPCs are using the IDL file to generate the needed interface to do the communication. Using XML-RPC or other technologies aren't an option.</p>
0
2009-10-07T22:59:40Z
1,534,704
<p>What kind of RPC are you thinking of? If it is XML-RPC, then Python comes with the <a href="http://docs.python.org/library/simplexmlrpcserver.html" rel="nofollow">SimpleXMLRPCServer</a> module, which, well, allows you to write RPC servers in Python.</p> <p>If the remote server uses DCOM, you can use <a href="http://oreilly.com/catalog/pythonwin32/chapter/ch12.html#60057" rel="nofollow">PythonCOM</a>.</p>
1
2009-10-07T23:04:38Z
[ "python", "rpc", "interprocess" ]
How to remove these duplicates in a list (python)
1,534,736
<pre><code>biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] </code></pre> <p>I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don't want duplicate "link" element. What is the most efficient code to do this so that it results in this:</p> <pre><code>biglist = [ {'title':'U2','link':'u2.com'}, {'title':'ABC','link':'abc.com'} ] </code></pre> <p>I have tried many ways, including using many nested "for ...in ...." but this is very inefficient and too long.</p>
1
2009-10-07T23:15:44Z
1,534,749
<p>Make a new dictionary, with 'u2.com' and 'abc.com' as the keys, and your list elements as the values. The dictionary will enforce uniqueness. Something like this:</p> <pre><code>uniquelist = dict((element['link'], element) for element in reversed(biglist)) </code></pre> <p>(The reversed is there so that the first elements in the list will be the ones that remain in the dictionary. If you take that out, then you will get the last element instead).</p> <p>Then you can get elements back into a list like this:</p> <pre><code>biglist = uniquelist.values() </code></pre>
3
2009-10-07T23:21:24Z
[ "python", "list" ]
How to remove these duplicates in a list (python)
1,534,736
<pre><code>biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] </code></pre> <p>I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don't want duplicate "link" element. What is the most efficient code to do this so that it results in this:</p> <pre><code>biglist = [ {'title':'U2','link':'u2.com'}, {'title':'ABC','link':'abc.com'} ] </code></pre> <p>I have tried many ways, including using many nested "for ...in ...." but this is very inefficient and too long.</p>
1
2009-10-07T23:15:44Z
1,534,751
<p>You can sort the list, using the <code>link</code> field of each dictionary as the sort key, then iterate through the list once and remove duplicates (or rather, create a new list with duplicates removed, as is the Python idiom), like so:</p> <pre><code># sort the list using the 'link' item as the sort key biglist.sort(key=lambda elt: elt['link']) newbiglist = [] for item in biglist: if newbiglist == [] or item['link'] != newbiglist[-1]['link']: newbiglist.append(item) </code></pre> <p>This code will give you the first element (relative ordering in the original <code>biglist</code>) for any group of "duplicates". This is true because the <code>.sort()</code> algorithm used by Python is guaranteed to be a stable sort -- it does not change the order of elements determined to be equal to one another (in this case, elements with the same <code>link</code>).</p>
2
2009-10-07T23:21:53Z
[ "python", "list" ]
How to remove these duplicates in a list (python)
1,534,736
<pre><code>biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] </code></pre> <p>I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don't want duplicate "link" element. What is the most efficient code to do this so that it results in this:</p> <pre><code>biglist = [ {'title':'U2','link':'u2.com'}, {'title':'ABC','link':'abc.com'} ] </code></pre> <p>I have tried many ways, including using many nested "for ...in ...." but this is very inefficient and too long.</p>
1
2009-10-07T23:15:44Z
1,534,787
<pre><code>biglist = \ [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] def dedupe(lst): d = {} for x in lst: link = x["link"] if link in d: continue d[link] = x return d.values() lst = dedupe(biglist) </code></pre> <p>dedupe() keeps the first of any duplicates.</p>
1
2009-10-07T23:32:42Z
[ "python", "list" ]
How to remove these duplicates in a list (python)
1,534,736
<pre><code>biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] </code></pre> <p>I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don't want duplicate "link" element. What is the most efficient code to do this so that it results in this:</p> <pre><code>biglist = [ {'title':'U2','link':'u2.com'}, {'title':'ABC','link':'abc.com'} ] </code></pre> <p>I have tried many ways, including using many nested "for ...in ...." but this is very inefficient and too long.</p>
1
2009-10-07T23:15:44Z
1,535,251
<p>Probably the fastest approach, for a really big list, if you want to preserve the exact order of the items that remain, is the following...:</p> <pre><code>biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] known_links = set() newlist = [] for d in biglist: link = d['link'] if link in known_links: continue newlist.append(d) known_links.add(link) biglist[:] = newlist </code></pre>
8
2009-10-08T02:08:34Z
[ "python", "list" ]
How to remove these duplicates in a list (python)
1,534,736
<pre><code>biglist = [ {'title':'U2 Band','link':'u2.com'}, {'title':'ABC Station','link':'abc.com'}, {'title':'Live Concert by U2','link':'u2.com'} ] </code></pre> <p>I would like to remove the THIRD element inside the list...because it has "u2.com" as a duplicate. I don't want duplicate "link" element. What is the most efficient code to do this so that it results in this:</p> <pre><code>biglist = [ {'title':'U2','link':'u2.com'}, {'title':'ABC','link':'abc.com'} ] </code></pre> <p>I have tried many ways, including using many nested "for ...in ...." but this is very inefficient and too long.</p>
1
2009-10-07T23:15:44Z
1,535,295
<p>You can use <code>defaultdict</code> to group items by <code>link</code>, then removed duplicates if you want to.</p> <pre><code>from collections import defaultdict nodupes = defaultdict(list) for d in biglist: nodupes[d['url']].append(d['title'] </code></pre> <p>This will give you:</p> <pre><code>defaultdict(&lt;type 'list'&gt;, {'abc.com': ['ABC Station'], 'u2.com': ['U2 Band', 'Live Concert by U2']}) </code></pre>
0
2009-10-08T02:22:41Z
[ "python", "list" ]
Need a workaround: Python's select.select() doesn't work with subprocess' stdout?
1,534,825
<p>From within my master python program, I am spawning a child program with this code:</p> <pre><code>child = subprocess.Popen(..., stdout=subprocess.PIPE, stdin=subprocess.PIPE) </code></pre> <p>FWIW, the child is a PHP script which needs to communicate back and forth with the python program.</p> <p>The master python program actually needs to listen for communication from several other channels - other PHP scripts spawned using the same code, or socket objects coming from <code>socket.accept()</code>, and I would like to use <code>select.select()</code> as that is the most efficient way to wait for input from a variety of sources.</p> <p>The problem I have, is that <code>select.select()</code> under Windows does not work with the subprocess' stdout file descriptor (this is documented), and it looks I will be forced to:</p> <ul> <li>A) Poll the PHP scripts to see if they have written anything to stdout. (This system needs to be very responsive, I would need to poll at least 1,000 times per second!)</li> <li>B) Have the PHP scripts connect to the master process and communicate via sockets instead of stdout/stdin.</li> </ul> <p>I will probably go with solution (B), because I can't bring myself to make the system poll at such a high frequency, but it seems a sad waste of resources to reconnect with sockets when stdout/stdin would have done just fine.</p> <p><strong>Is there some alternative solution which would allow me to use stdout <em>and</em> <code>select.select()</code>?</strong></p>
1
2009-10-07T23:44:32Z
1,534,844
<p>Unfortunately, many uses of pipes on Windows don't work as nicely as they do on Unix, and this is one of them. On Windows, the better solution is probably to have your master program spawn threads to listen to each of its subprocesses. If you know the granularity of data that you expect back from your subprocess, you can do blocking reads in each of your threads, and then the thread will come alive when the IO unblocks.</p> <p>Alternatively, (I have no idea if this is viable for your project), you could look into using a Unix-like system, or a Unix-like layer on top of Windows (e.g. Cygwin), where <code>select.select()</code> will work on subprocess pipes.</p>
4
2009-10-07T23:49:49Z
[ "python", "sockets", "select", "subprocess" ]
How to transform Python 3 script to Mac OS application bundle?
1,534,933
<p>Is there currently a way to create an application bundle from Py3k script? py2app uses Carbon package and therefore, as far as I understand, cannot be ported to py3k - Carbon development was terminated.</p>
1
2009-10-08T00:13:07Z
1,535,269
<p>I have not checked if that's true, but <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">cx_freeze</a> 4.1 claims to support Python 3.1 (<code>cx_freeze</code> in general has long supported Mac OS X, as well as Windows and Linux, and I believe that also applies to the recent 4.1 release).</p>
0
2009-10-08T02:15:51Z
[ "python", "osx" ]
How to transform Python 3 script to Mac OS application bundle?
1,534,933
<p>Is there currently a way to create an application bundle from Py3k script? py2app uses Carbon package and therefore, as far as I understand, cannot be ported to py3k - Carbon development was terminated.</p>
1
2009-10-08T00:13:07Z
1,552,199
<p>There's always Platypus and PyObjC</p> <p><a href="http://www.sveinbjorn.org/platypus" rel="nofollow">http://www.sveinbjorn.org/platypus</a></p> <p><a href="http://pyobjc.sourceforge.net" rel="nofollow">http://pyobjc.sourceforge.net</a></p>
1
2009-10-12T00:29:04Z
[ "python", "osx" ]
How to trim a list in Python
1,534,939
<p>Suppose I have a list with X elements</p> <pre><code>[4,76,2,8,6,4,3,7,2,1...] </code></pre> <p>I'd like the first 5 elements. Unless it has less than 5 elements.</p> <pre><code>[4,76,2,8,6] </code></pre> <p>How to do that?</p>
14
2009-10-08T00:14:38Z
1,534,956
<pre><code>l = [4,76,2,8,6,4,3,7,2,1] l = l[:5] </code></pre>
0
2009-10-08T00:17:33Z
[ "python", "list" ]
How to trim a list in Python
1,534,939
<p>Suppose I have a list with X elements</p> <pre><code>[4,76,2,8,6,4,3,7,2,1...] </code></pre> <p>I'd like the first 5 elements. Unless it has less than 5 elements.</p> <pre><code>[4,76,2,8,6] </code></pre> <p>How to do that?</p>
14
2009-10-08T00:14:38Z
1,534,957
<p>You just subindex it with <code>[:5]</code> indicating that you want (up to) the first 5 elements.</p> <pre><code>&gt;&gt;&gt; [1,2,3,4,5,6,7,8][:5] [1, 2, 3, 4, 5] &gt;&gt;&gt; [1,2,3][:5] [1, 2, 3] &gt;&gt;&gt; x = [6,7,8,9,10,11,12] &gt;&gt;&gt; x[:5] [6, 7, 8, 9, 10] </code></pre> <p>Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!</p> <pre><code>&gt;&gt;&gt; x[5:] [11, 12] </code></pre>
41
2009-10-08T00:17:36Z
[ "python", "list" ]
How to trim a list in Python
1,534,939
<p>Suppose I have a list with X elements</p> <pre><code>[4,76,2,8,6,4,3,7,2,1...] </code></pre> <p>I'd like the first 5 elements. Unless it has less than 5 elements.</p> <pre><code>[4,76,2,8,6] </code></pre> <p>How to do that?</p>
14
2009-10-08T00:14:38Z
1,534,958
<pre><code>&gt;&gt;&gt; [1,2,3,4,5,6,7,8,9][:5] [1, 2, 3, 4, 5] &gt;&gt;&gt; [1,2,3][:5] [1, 2, 3] </code></pre>
1
2009-10-08T00:17:45Z
[ "python", "list" ]
How to trim a list in Python
1,534,939
<p>Suppose I have a list with X elements</p> <pre><code>[4,76,2,8,6,4,3,7,2,1...] </code></pre> <p>I'd like the first 5 elements. Unless it has less than 5 elements.</p> <pre><code>[4,76,2,8,6] </code></pre> <p>How to do that?</p>
14
2009-10-08T00:14:38Z
4,339,929
<p>To trim a list in place without creating copies of it, use <code>del</code>:</p> <pre><code>&gt;&gt;&gt; t = [1, 2, 3, 4, 5] &gt;&gt;&gt; # delete elements starting from index 4 to the end &gt;&gt;&gt; del t[4:] &gt;&gt;&gt; t [1, 2, 3, 4] &gt;&gt;&gt; # delete elements starting from index 5 to the end &gt;&gt;&gt; # but the list has only 4 elements -- no error &gt;&gt;&gt; del t[5:] &gt;&gt;&gt; t [1, 2, 3, 4] &gt;&gt;&gt; </code></pre>
11
2010-12-02T21:09:43Z
[ "python", "list" ]
Jump to Model/View/Controller in emacs
1,534,969
<p>Most rails modes for emacs have this kind of functionality. You are in a controller file over a function "<strong>kaboosh</strong>" in "app/controller/<strong>bla.rb</strong>" and with a keyboard shortcut you switch to "app/views/<strong>kaboosh</strong>.erb" or to app/models/<strong>bla.rb</strong>".</p> <p>A similar functionality exists for .c and .h files using <strong>ff-find-other-file</strong>.</p> <p>I checked jump.el and findr.el but all seems a little bit complicated. I tried searching this for django projects (it would have helped a lot) but no luck.</p> <p>Anyone knows a simple way (etags?) that it's easy to define the connection between current file/function and target file and then bind it to a keyboard shortcut?</p>
1
2009-10-08T00:22:21Z
1,535,684
<p><a href="http://www.gnu.org/software/emacs/manual/html%5Fnode/emacs/Find-Tag.html#Find-Tag" rel="nofollow">Tags</a> is set up well to jump you to the definition of a function. <code>M-.</code> will take you to the first occurrence of a function definition, <code>C-u M-.</code> will take you to the next (and one after that, and after that...). Perhaps the <code>C-u M-.</code> solves some of your problem.</p> <p>Regarding associations between files, and wanting a rails like interface, it looks like you could pull out the appropriate chunks of code and customize them for python.</p> <p>Specifically, you'll need the <a href="http://github.com/botanicus/dotfiles/tree/7a8cbdaabf491d92d01ae7c4099d3850ec26cc16/emacs/emacs.d/elpa/jump-2.0" rel="nofollow">jump</a> package, make a similar jump schema like the <code>rinari-jump-schema</code> (found in rinari.el). The jump schema uses <code>'ruby-add-log-current-method</code> (found in ruby-mode.el), and you'd just need to customize that to return the current method name for Python syntax.</p> <p>It doesn't look like anyone has done this for Python yet, you could be the first. I believe those are the only pieces you'll need.</p>
1
2009-10-08T04:48:31Z
[ "python", "emacs" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
1,535,013
<p>Is <code>some_widget_instance</code> and instance of <code>Widget</code> or of <code>WidgetFile</code> ? Because if it is an instance of <code>Widget</code> it won't get your custom <code>delete()</code> function, which is in the <code>WidgetFile</code> class.</p>
1
2009-10-08T00:44:39Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
1,535,032
<p>This seems only be sense-full if one Widget is connected to one WidgetFile exactly. In that case you should use a <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#one-to-one-relationships" rel="nofollow">OneToOneField</a></p> <p>from <a href="http://www.djangoproject.com/documentation/models/one%5Fto%5Fone/" rel="nofollow">On-to-one examples:</a></p> <pre><code># Delete the restaurant; the waiter should also be removed &gt;&gt;&gt; r = Restaurant.objects.get(pk=1) &gt;&gt;&gt; r.delete() </code></pre>
1
2009-10-08T00:52:17Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
1,535,066
<p>Just to throw in a possible way around this problem: <a href="http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_delete" rel="nofollow">pre-delete</a> <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">signal</a>. (Not in any way implying there's no actual solution.)</p>
1
2009-10-08T01:04:50Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
1,535,451
<p>Using <code>clear()</code> prior to deleting, removes all objects from the related object set.</p> <p>see <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward" rel="nofollow">django-following-relationships-backward</a></p> <p>example:</p> <pre><code>group.link_set.clear() group.delete() </code></pre>
2
2009-10-08T03:21:39Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
1,539,182
<p>I figured it out. I just put this on that Widget model:</p> <pre><code>def delete(self): files = WidgetFile.objects.filter(widget=self) if files: for file in files: file.delete() super(Widget, self).delete() </code></pre> <p>This triggered the necessary delete() method on each of the related objects, thus triggering my custom file deleting code. It's more database expensive yes, but when you're trying to delete files on a hard drive anyway, it's not such a big expense to hit the db a few extra times.</p>
19
2009-10-08T17:05:11Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
6,121,651
<p>It should look like described on the <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods" rel="nofollow">django</a> site:</p> <pre><code>class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def save(self, *args, **kwargs): do_something() super(Blog, self).save(*args, **kwargs) # Call the "real" save() method. do_something_else() </code></pre> <p><a href="http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods</a></p> <p>you forgot to pass some arguments</p>
1
2011-05-25T08:35:25Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
12,678,428
<p>I'm doing the same thing and noticed a nugget in the Django docs that you should think about.</p> <p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods">Overriding predefined model methods</a></p> <blockquote> <p>Overriding Delete Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.</p> </blockquote> <p>This means your snippet will not <em>always</em> do what you want. Using <a href="https://docs.djangoproject.com/en/dev/ref/signals/">Signals</a> is a better option for dealing with deletions.</p> <p>I went with the following:</p> <pre><code>import shutil from django.db.models.signals import pre_delete from django.dispatch import receiver @receiver(pre_delete) def delete_repo(sender, instance, **kwargs): if sender == Set: shutil.rmtree(instance.repo) </code></pre>
41
2012-10-01T17:55:56Z
[ "python", "django", "django-models", "method-overloading" ]
How do I override delete() on a model and have it still work with related deletes
1,534,986
<p>I'm having a problem because I'm deleting a Widget by using some_widget_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles related to it like this:</p> <pre><code>class WidgetFile(models.Model): widget = models.ForeignKey(Widget) </code></pre> <p>Well, when I delete that Widget, it's WidgetFiles are deleted but the delete() method doesn't trigger and do my extra hard drive stuff. Any help is much appreciated.</p>
15
2009-10-08T00:31:38Z
36,510,139
<p>From Django 1.9, if You would just define <code>on_delete=models.CASCADE</code> for field, it will remove all related objects on delete.</p>
0
2016-04-08T22:11:11Z
[ "python", "django", "django-models", "method-overloading" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,535,302
<p>Well if you happen to go the PHP route you could use an <a href="http://us.php.net/manual/en/ref.sqlite.php" rel="nofollow">SQLite</a> database, however MySQL is a perfectly reasonable way to store that info and usually (at least from the ones I've seen) is how it is done.</p> <p>If you didn't want to store IP address and any other info a simple number in a text file could work.</p>
-1
2009-10-08T02:25:42Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,535,311
<p>A fascinating subject. Incrementing a counter, simple as it may be, just <em>has</em> to be a transaction... meaning, it can lock out the whole DB for longer than makes sense!-) It can easily be the bottleneck for the whole system.</p> <p>If you need rigorously exact counts but don't need them to be instantly up-to-date, my favorite approach is to append the countable information to a log (switching logs as often as needed for data freshness purposes). Once a log is closed (with thousands of countable events in it), a script can read it and update all that's needed in a single transaction -- maybe not intuitive, but much faster than thousands of single locks.</p> <p>Then there's extremely-fast counters that are only <em>statistically</em> accurate -- but since you don't say that such imprecision is acceptable, I'm not going to explain them in more depth.</p>
7
2009-10-08T02:28:22Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,535,408
<p>There are two really easy ways:</p> <ol> <li>Parse it out of your web logs in batch.</li> <li>Run the hits through <a href="http://kr.github.com/beanstalkd/" rel="nofollow">beanstalkd</a> or <a href="http://gearman.org/" rel="nofollow">gearmand</a> and have a worker do the hard stuff in a controlled way.</li> </ol> <p>Option 1 works with off-the-shelf tools. Option 2 requires just a bit of programming, but gives you something closer to realtime updates without causing you to fall over when the traffic spikes (such as you'll find in your direct mysql case).</p>
2
2009-10-08T03:06:30Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,535,419
<p>Not sure if it's up your alley, but AppEngine is a pretty nice platform to build on. Some sample code you can use to build a counter using their DataStore and transactions is described here: <a href="http://code.google.com/appengine/docs/python/datastore/transactions.html" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/transactions.html</a>.</p>
0
2009-10-08T03:09:43Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,535,794
<p>If accuracy is important, you can do it slightly slower with MySql... create a HEAP / Memory table to store your counter values. These a in-memory tables that are blazingly fast. You can write the data into a normal table at intervals. </p> <p>Based on the app engine ideas, you could use memcache as a temporary store for your counter. Incrementing a memcache counter is faster than using the MySql heap tables (I think). Once every five or ten seconds, you could read the memcache counter and write that number into your DB. </p>
1
2009-10-08T05:34:53Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,536,049
<p>You could take your webserver's <strong>Access log</strong> (Apache: access.log) and evaluate it time and again (cronjob) in case you do not need to have the data at hand at the exact moment in time when someone visits your site.</p> <p>Usually, the access.log is generated anyway and contains the requested resource as well as time, date and the user's IP. This way you do not have to route all trafic through a php-script. Lean, mean counting machine.</p>
4
2009-10-08T06:59:13Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,900,253
<p>You can use <a href="http://code.google.com/p/redis/" rel="nofollow">Redis</a> - it`s very fast key-value storage with support for atomic increments. If need will arise -- counts data could be splitted between multiple servers easily.</p>
0
2009-12-14T11:05:42Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
1,900,337
<p>I've done something very similar, on a similar scale (multiple servers, hundreds of domains, several thousand hits per hour) and log file analysis was definitely the way to go. (It also checked hit rates, weighted them by file type, and blacklisted IP addresses at the firewall if they were making too many requests; its intended purpose was to auto-block bad bots, not to just be a counter, but counting was an essential piece of it.)</p> <p>No performance impact on the web server process itself, since it's not doing any additional work there, and you could easily publish periodically-updated hit counts by injecting them into the site's database every minute/5 minutes/100 hits/whatever without having to lock the relevant row/table/database (depending on the locking mechanism in use) on every hit.</p>
0
2009-12-14T11:21:55Z
[ "php", "python", "mysql", "tracking" ]
How to write an efficient hit counter for websites
1,535,261
<p>I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second. </p> <p>I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using MySQL to keep track of this, but I'm guessing there's a more efficient way. What are good methods of keeping counters?</p>
5
2009-10-08T02:12:09Z
2,027,895
<p>Without a doubt, Redis is perfect for this problem. It requires about a minute to setup and install, supports atomic increments, is incredibly fast, has client libs for python and php (and many other languages), is durable (snapshots, journal, replication). </p> <p>Store each counter to its own key. Then simply</p> <pre><code>INCR key </code></pre>
2
2010-01-08T13:41:57Z
[ "php", "python", "mysql", "tracking" ]
Python instance method making multiple instance method calls
1,535,313
<p>Here is some snippet code. I have tested the methods listed and they work correctly, yet when I run and test this method (<code>countLOC</code>) it only seems to initialize the first variable that has an instance method call (<code>i = self.countBlankLines()</code>). Anyone know the obvious reason I'm obviously missing? </p> <pre><code>def countLOC(self): i = self.countBlankLines() j = self.countDocStringLines() k = self.countLines() p = self.countCommentLines() return k-i-j-p </code></pre> <p>This returns -3 because <code>countBlankLines()</code> returns 3 (correctly). however, it should return 37 as <code>countDocStringLines()</code> = 6 and <code>countCommentLines()</code> = 4 while <code>countLines()</code> = 50. Thanks.</p>
0
2009-10-08T02:29:40Z
1,535,388
<p>If local variables were not initialized (impossible given your code!) they wouldn't be 0 -- rather, you'd get a NameError exception when you try to use them. It's 100% certain that those other method calls (except the first one) are returning 0 (or numbers totaling to 0 in the expression).</p> <p>Hard to guess, not being shown their code, but from your comment my crystal ball tells me you have an iterator as an instance variable: the first method to iterate on it exhausts it, the other methods therefore find it empty.</p>
5
2009-10-08T03:00:22Z
[ "python", "methods", "method-call" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
1,535,336
<pre><code>&gt;&gt;&gt; class Test: ... def __repr__(self): ... return "Test()" ... def __str__(self): ... return "member of Test" ... &gt;&gt;&gt; t = Test() &gt;&gt;&gt; t Test() &gt;&gt;&gt; print t member of Test </code></pre> <p>The <code>__str__</code> method is what happens when you print it, and the <code>__repr__</code> method is what happens when you use the <code>repr()</code> function (or when you look at it with the interactive prompt). If this isn't the most <em>Pythonic</em> method, I apologize, because I'm still learning too - but it works.</p> <p>If no <code>__str__</code> method is given, Python will print the result of <code>__repr__</code> instead. If you define <code>__str__</code> but not <code>__repr__</code>, Python will use what you see above as the <code>__repr__</code>, but still use <code>__str__</code> for printing.</p>
247
2009-10-08T02:39:35Z
[ "python", "class", "printing", "object" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
1,535,375
<p>As Chris Lutz mentioned, this is defined by the <code>__repr__</code> method in your class.</p> <p>From the documentation of <a href="http://docs.python.org/library/functions.html#repr"><code>repr()</code></a>:</p> <blockquote> <p>For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to <code>eval()</code>, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a <code>__repr__()</code> method.</p> </blockquote> <p>Given the following class Test:</p> <pre><code>class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return "&lt;Test a:%s b:%s&gt;" % (self.a, self.b) def __str__(self): return "From str method of Test: a is %s, b is %s" % (self.a, self.b) </code></pre> <p>..it will act the following way in the Python shell:</p> <pre><code>&gt;&gt;&gt; t = Test(123, 456) &gt;&gt;&gt; t &lt;Test a:123 b:456&gt; &gt;&gt;&gt; print repr(t) &lt;Test a:123 b:456&gt; &gt;&gt;&gt; print t From str method of Test: a is 123, b is 456 &gt;&gt;&gt; print str(t) From str method of Test: a is 123, b is 456 </code></pre> <p>If no <code>__str__</code> method is defined, <code>print t</code> (or <code>print str(t)</code>) will use the result of <code>__repr__</code> instead</p> <p>If no <code>__repr__</code> method is defined then the default is used, which is pretty much equivalent to..</p> <pre><code>def __repr__(self): return "&lt;%s instance at %s&gt;" % (self.__class__.__name__, id(self)) </code></pre>
66
2009-10-08T02:55:04Z
[ "python", "class", "printing", "object" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
13,971,187
<p>Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:</p> <blockquote> <p>"[...] to return a string that would yield an object with the same value when passed to eval(), [...]"</p> </blockquote> <p>Given this class definition:</p> <pre><code>class Test(object): def __init__(self, a, b): self._a = a self._b = b def __str__(self): return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b) def __repr__(self): return 'Test("%s","%s")' % (self._a, self._b) </code></pre> <p>Now, is easy to serialize instance of <code>Test</code> class:</p> <pre><code>x = Test('hello', 'world') print 'Human readable: ', str(x) print 'Object representation: ', repr(x) print y = eval(repr(x)) print 'Human readable: ', str(y) print 'Object representation: ', repr(y) print </code></pre> <p>So, running last piece of code, we'll get:</p> <pre><code>Human readable: An instance of class Test with state: a=hello b=world Object representation: Test("hello","world") Human readable: An instance of class Test with state: a=hello b=world Object representation: Test("hello","world") </code></pre> <p>But, as I said in my last comment: more info is just <a href="http://stackoverflow.com/a/2626364/68269">here</a>!</p>
8
2012-12-20T11:27:39Z
[ "python", "class", "printing", "object" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
14,354,579
<p>You need to use <code>__repr__</code>. This is a standard function like <code>__init__</code>. For example:</p> <pre><code>class Foobar(): """This will create Foobar type object.""" def __init__(self): print "Foobar object is created." def __repr__(self): return "Type what do you want to see here." a = Foobar() print a </code></pre>
9
2013-01-16T09:04:00Z
[ "python", "class", "printing", "object" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
31,800,938
<p>There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.</p> <p>You just have to make sure you have parentheses at the end of your class, e.g:</p> <pre><code>print(class()) </code></pre> <p>Here's an example of code from a project I was working on:</p> <pre><code>class Element: def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number def __str__(self): return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number class Hydrogen(Element): def __init__(self): super().__init__(name = "Hydrogen", symbol = "H", number = "1") </code></pre> <p>To print my Hydrogen class, I used the following:</p> <pre><code>print(Hydrogen()) </code></pre> <p>Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.</p> <p>Hope this helps, let me know if you have anymore questions. </p>
1
2015-08-04T04:52:21Z
[ "python", "class", "printing", "object" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
32,635,523
<p>A generic way that can be applied to any class without specific formatting could be done as follows:</p> <pre><code>class Element: def __init__(self, name, symbol, number): self.name = name self.symbol = symbol self.number = number def __str__(self): return str(self.__class__) + ": " + str(self.__dict__) </code></pre> <p>And then,</p> <pre><code>elem = Element('my_name', 'some_symbol', 3) print(elem) </code></pre> <p>produces</p> <pre><code>__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3} </code></pre>
3
2015-09-17T16:35:05Z
[ "python", "class", "printing", "object" ]
How to print a class or objects of class using print()?
1,535,327
<p>I am learning the ropes in Python. When I try to print an object of class <strong><code>Foobar</code></strong> using the <strong><code>print()</code></strong> function, I get an output like this:</p> <pre><code>&lt;__main__.Foobar instance at 0x7ff2a18c&gt; </code></pre> <p>Is there a way I can set the <em>printing behaviour</em> (or the <em>string representation</em>) of a <em>class</em> and its <em>objects</em>? For instance, when I call <code>print()</code> on a class object, I would like to print its data members in a certain format. How to achieve this in Python?</p> <p>If you are familiar with C++ classes, the above can be achieved for the standard <strong><code>ostream</code></strong> by adding a <strong><code>friend ostream&amp; operator &lt;&lt; (ostream&amp;, const Foobar&amp;)</code></strong> method for the class.</p>
236
2009-10-08T02:35:30Z
37,349,332
<p>For Python 3:</p> <p>If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object. </p> <p>Inspired by <a href="http://stackoverflow.com/a/23851642/635906">this</a> answer</p> <pre><code>class Printable: def __repr__(self): from pprint import pformat return "&lt;" + type(self).__name__ + "&gt; " + pformat(vars(self), indent=4, width=1) # Example Usage class MyClass(Printable): pass my_obj = MyClass() my_obj.msg = "Hello" my_obj.number = "46" print(my_obj) </code></pre>
2
2016-05-20T14:26:51Z
[ "python", "class", "printing", "object" ]
Resource scheduling application
1,535,391
<p>I'm trying to implement an application that coordinates multiple users who are scheduling exclusive resources. The schedule data must maintain strong consistency over a network with a single master node. The scheduled resources could be anything from a conference room to a worker on a job site.</p> <p>We assume the conference room cannot be scheduled for two meetings at once and a worker cannot be on two job sites at the same time. The business logic of the application must not allow a user to "overbook" a resource.</p> <p>What I can't figure out is how to represent the data so that if two or more users operate on the schedule at the same time, and there are conflicts, one of the updates will abort.</p> <p>The only solution I've seen so far is to track time slots for each exclusionary resource. So if the conference room is used on 5 min intervals, and it was scheduled for 9-9:30am, then the corresponding 5 minute time slots for 9-9:30am would all return TRUE, while the unscheduled slots would return FALSE or NULL. The DB transaction would then pull the conference room object out of the store, check all the time slots, and abort if the update conflicted with existing time slots.</p> <p>However, this seems like it will get really big, really fast. Perhaps it could be garbage collected? Also, one of the goals of the design is to support variable granularity, so some objects will get scheduled on a minute to minute basis while others could be on a day to day basis, and this data design does not support that very well.</p> <p>Currently, I am trying to implement this on Google App Engine using Python, but I would be really interested to see some more general solutions to this problem. All I've come up with Googling is scheduling recurring tasks, or algorithms that perform one time operations to automatically build optimized schedules.</p>
1
2009-10-08T03:01:12Z
1,535,554
<p>You'll want to track just start and end times for each exclusionary resource. The data storage in your problem is actually the easy part - the hard(er) part is crafting queries to look for conflicts in time intervals.</p> <p>If my logic is correct after being up for 21 hours, the following psuedo-code should check for meeting conflicts.</p> <pre><code># Set up your proposed meeting proposed.start = &lt;thursday, 1pm&gt; proposed.end = &lt;thursday, 2pm&gt; # Look for meetings that intersect with or straddle proposed meeting conflicts = &lt;SELECT * FROM meeting WHERE meeting.start BETWEEN proposed.start AND proposed.end OR meeting.end BETWEEN proposed.start AND proposed.end OR meeting.start &lt;= proposed.start AND meeting.end &gt;= proposed.end&gt; if conflicts.length &gt; 0: # We have a conflict! </code></pre>
3
2009-10-08T04:00:23Z
[ "python", "google-app-engine", "resources", "scheduling", "schedule" ]
Resource scheduling application
1,535,391
<p>I'm trying to implement an application that coordinates multiple users who are scheduling exclusive resources. The schedule data must maintain strong consistency over a network with a single master node. The scheduled resources could be anything from a conference room to a worker on a job site.</p> <p>We assume the conference room cannot be scheduled for two meetings at once and a worker cannot be on two job sites at the same time. The business logic of the application must not allow a user to "overbook" a resource.</p> <p>What I can't figure out is how to represent the data so that if two or more users operate on the schedule at the same time, and there are conflicts, one of the updates will abort.</p> <p>The only solution I've seen so far is to track time slots for each exclusionary resource. So if the conference room is used on 5 min intervals, and it was scheduled for 9-9:30am, then the corresponding 5 minute time slots for 9-9:30am would all return TRUE, while the unscheduled slots would return FALSE or NULL. The DB transaction would then pull the conference room object out of the store, check all the time slots, and abort if the update conflicted with existing time slots.</p> <p>However, this seems like it will get really big, really fast. Perhaps it could be garbage collected? Also, one of the goals of the design is to support variable granularity, so some objects will get scheduled on a minute to minute basis while others could be on a day to day basis, and this data design does not support that very well.</p> <p>Currently, I am trying to implement this on Google App Engine using Python, but I would be really interested to see some more general solutions to this problem. All I've come up with Googling is scheduling recurring tasks, or algorithms that perform one time operations to automatically build optimized schedules.</p>
1
2009-10-08T03:01:12Z
2,036,990
<p>To automatically optimize a timetable of a school or university (or even other problems) take a look at the following Java tools: </p> <p><a href="http://timefinder.sourceforge.net/" rel="nofollow">TimeFinder</a>, <a href="http://www.unitime.org/index.php?tab=1" rel="nofollow">UniTime</a> or <a href="http://www.jboss.org/drools/drools-solver.html" rel="nofollow">Drools Solver</a></p> <p>The problem with user interaction is not as easiely solved as you explained I think, because there could be other constraint violations as well (timetabling can get a lot more complicated).</p> <p>First, I would only allow timetablers accessing/changing the timetable data.</p> <p>Second, I would create an independent solution for each timetabler and then optimize this solution with the proposed tools above. The solutions then can be stored to the database and the timetabler could use them to further optimize the schedule or to compare to other solutions.</p>
1
2010-01-10T12:26:39Z
[ "python", "google-app-engine", "resources", "scheduling", "schedule" ]
Python Documentation Refers You To Docs for "the C function wait." Where is that?
1,535,564
<p>There's multiple places in the Python documentation where it refers you to the C function "wait." For instance: "The exit status for the command can be interpreted according to the rules for the C function wait," in the <a href="http://docs.python.org/library/commands.html" rel="nofollow">commands</a> and <a href="https://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> modules.</p> <p>Where can I find this documentation? Apparently my Google-fu is not strong enough, or it's late enough at night that I'm being dumb. (But I figure this is probably a question that should be in Stack Overflow anyway.)</p>
4
2009-10-08T04:05:04Z
1,535,568
<p><code>$ man 2 wait</code> (on Linux and Unix systems).</p>
4
2009-10-08T04:06:18Z
[ "python", "c", "documentation", "subprocess" ]
Python Documentation Refers You To Docs for "the C function wait." Where is that?
1,535,564
<p>There's multiple places in the Python documentation where it refers you to the C function "wait." For instance: "The exit status for the command can be interpreted according to the rules for the C function wait," in the <a href="http://docs.python.org/library/commands.html" rel="nofollow">commands</a> and <a href="https://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> modules.</p> <p>Where can I find this documentation? Apparently my Google-fu is not strong enough, or it's late enough at night that I'm being dumb. (But I figure this is probably a question that should be in Stack Overflow anyway.)</p>
4
2009-10-08T04:05:04Z
1,535,574
<p>A search for <code>man wait</code> gives <a href="http://www.manpagez.com/man/2/wait/" rel="nofollow">this</a> as the top hit -- <code>man</code> is the Unix command for getting the manual page of something, so a search for <code>man foobar</code> is likely to reveal manual pages for <code>foobar</code> that happen to be online.</p>
3
2009-10-08T04:07:31Z
[ "python", "c", "documentation", "subprocess" ]
Python Documentation Refers You To Docs for "the C function wait." Where is that?
1,535,564
<p>There's multiple places in the Python documentation where it refers you to the C function "wait." For instance: "The exit status for the command can be interpreted according to the rules for the C function wait," in the <a href="http://docs.python.org/library/commands.html" rel="nofollow">commands</a> and <a href="https://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> modules.</p> <p>Where can I find this documentation? Apparently my Google-fu is not strong enough, or it's late enough at night that I'm being dumb. (But I figure this is probably a question that should be in Stack Overflow anyway.)</p>
4
2009-10-08T04:05:04Z
1,535,577
<p><a href="http://www.manpagez.com/man/2/wait/" rel="nofollow">http://www.manpagez.com/man/2/wait/</a></p> <p>(and at many other sources of <code>man</code> pages on the Internet).</p>
1
2009-10-08T04:08:44Z
[ "python", "c", "documentation", "subprocess" ]
Python Documentation Refers You To Docs for "the C function wait." Where is that?
1,535,564
<p>There's multiple places in the Python documentation where it refers you to the C function "wait." For instance: "The exit status for the command can be interpreted according to the rules for the C function wait," in the <a href="http://docs.python.org/library/commands.html" rel="nofollow">commands</a> and <a href="https://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> modules.</p> <p>Where can I find this documentation? Apparently my Google-fu is not strong enough, or it's late enough at night that I'm being dumb. (But I figure this is probably a question that should be in Stack Overflow anyway.)</p>
4
2009-10-08T04:05:04Z
1,535,583
<p>Here are some online pages for Linux...</p> <p><a href="http://manpages.ubuntu.com/manpages/jaunty/en/man2/wait.2.html" rel="nofollow">http://manpages.ubuntu.com/manpages/jaunty/en/man2/wait.2.html</a></p> <p>Sometimes the BSD pages have fewer extensions. They aren't always closer to pure posix but they are sometimes more "common denominator unix".</p> <p><a href="http://netbsd.gw.com/cgi-bin/man-cgi?wait+2+NetBSD-current" rel="nofollow">http://netbsd.gw.com/cgi-bin/man-cgi?wait+2+NetBSD-current</a></p> <p>There was a time that <code>man 2 wait</code> would give you the answer on every unix box. However, these days the man pages are typically an optional package which you will have to hunt down, or at least identify its name. Because these change slightly over time they are associated with a given release of the OS, so there is no central authority. For typical use today in process management with scripting languages you may want to actually check with one of the various standards bodies, perhaps at <a href="http://www.opengroup.org/onlinepubs/009695399/functions/wait.html" rel="nofollow">http://www.opengroup.org/onlinepubs/009695399/functions/wait.html</a> Finally, I should add that you can get these for cygwin on windows.</p>
4
2009-10-08T04:11:09Z
[ "python", "c", "documentation", "subprocess" ]
How to interpret status code in Python commands.getstatusoutput()
1,535,672
<p>In a <a href="http://stackoverflow.com/questions/1535564">related question</a>, I asked where to find the documentation for the C function "wait." This was an attempt to figure out return codes for the commands.getstatusoutput() module. Stackoverflow came through, but the documentation didn't help. Here's what puzzles me:</p> <pre><code>#!/usr/bin/python import commands goodcommand = 'ls /' badcommand = 'ls /fail' status, output = commands.getstatusoutput(goodcommand) print('Good command reported status of %s' % status) status, output = commands.getstatusoutput(badcommand) print('Bad command reported status of %s' % status) </code></pre> <p>When run on OS X (Leopard) I get the following output: (Which matches the documentation.)</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 256 </code></pre> <p>On OS X, doing an "ls /fail ; echo $?" gets the following output:</p> <pre><code>$ ls /fail ; echo $? ls: /fail: No such file or directory 1 </code></pre> <p>When run on Linux (Ubuntu Hardy) I get the following output:</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 512 </code></pre> <p>On Ubuntu, doing "ls /fail" gets a 2:</p> <pre><code>$ ls /fail ; echo $? ls: cannot access /fail: No such file or directory 2 </code></pre> <p>So Python appears to be multiplying status codes by 256. Huh? Is this documented somewhere?</p>
4
2009-10-08T04:43:50Z
1,535,675
<p>Wow. The insight that it was multiplying by 256 got me there. Searching for "python commands +256" got me to a <a href="http://www.doughellmann.com/PyMOTW/commands/index.html" rel="nofollow">Python Module Of The Week</a> article which explains what's going on.</p> <p>Here's a snippet from that page:</p> <blockquote> <p>The function getstatusoutput() runs a command via the shell and returns the exit code and the text output (stdout and stderr combined). The exit codes are the same as for the C function wait() or os.wait(). The code is a 16-bit number. The low byte contains the signal number that killed the process. When the signal is zero, the high byte is the exit status of the program. If a core file was produced, the high bit of the low byte is set.</p> </blockquote> <p>And some of Doug's code:</p> <pre><code>from commands import * def run_command(cmd): print 'Running: "%s"' % cmd status, text = getstatusoutput(cmd) exit_code = status &gt;&gt; 8 signal_num = status % 256 print 'Signal: %d' % signal_num print 'Exit : %d' % exit_code print 'Core? : %s' % bool(exit_code / 256) print 'Output:' print text print run_command('ls -l *.py') run_command('ls -l *.notthere') run_command('echo "WAITING TO BE KILLED"; read input') </code></pre>
3
2009-10-08T04:44:39Z
[ "python", "documentation", "subprocess", "command", "exit-code" ]
How to interpret status code in Python commands.getstatusoutput()
1,535,672
<p>In a <a href="http://stackoverflow.com/questions/1535564">related question</a>, I asked where to find the documentation for the C function "wait." This was an attempt to figure out return codes for the commands.getstatusoutput() module. Stackoverflow came through, but the documentation didn't help. Here's what puzzles me:</p> <pre><code>#!/usr/bin/python import commands goodcommand = 'ls /' badcommand = 'ls /fail' status, output = commands.getstatusoutput(goodcommand) print('Good command reported status of %s' % status) status, output = commands.getstatusoutput(badcommand) print('Bad command reported status of %s' % status) </code></pre> <p>When run on OS X (Leopard) I get the following output: (Which matches the documentation.)</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 256 </code></pre> <p>On OS X, doing an "ls /fail ; echo $?" gets the following output:</p> <pre><code>$ ls /fail ; echo $? ls: /fail: No such file or directory 1 </code></pre> <p>When run on Linux (Ubuntu Hardy) I get the following output:</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 512 </code></pre> <p>On Ubuntu, doing "ls /fail" gets a 2:</p> <pre><code>$ ls /fail ; echo $? ls: cannot access /fail: No such file or directory 2 </code></pre> <p>So Python appears to be multiplying status codes by 256. Huh? Is this documented somewhere?</p>
4
2009-10-08T04:43:50Z
1,535,695
<p>Looking at <code>commands.py</code>:</p> <pre><code>def getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" import os pipe = os.popen('{ ' + cmd + '; } 2&gt;&amp;1', 'r') text = pipe.read() sts = pipe.close() if sts is None: sts = 0 if text[-1:] == '\n': text = text[:-1] return sts, text </code></pre> <p>We see <code>sts</code> holds the value of <code>os.popen(...).close()</code>. Looking at <a href="http://docs.python.org/library/os.html#os.popen" rel="nofollow"><em>that</em> documentation</a>, <code>os.popen(...).close()</code> returns the value of <a href="http://docs.python.org/library/os.html#os.wait" rel="nofollow"><code>os.wait</code></a>:</p> <blockquote> <p><code>os.wait()</code></p> <p>Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and <strong>whose high byte is the exit status</strong> (if the signal number is zero); the high bit of the low byte is set if a core file was produced. Availability: Unix.</p> </blockquote> <p>Emphasis was mine. I agree that this "encoding" isn't terribly intuitive, but at least it was fairly obvious at a glance that it was being multiplied/bit-shifted.</p>
4
2009-10-08T04:51:46Z
[ "python", "documentation", "subprocess", "command", "exit-code" ]
How to interpret status code in Python commands.getstatusoutput()
1,535,672
<p>In a <a href="http://stackoverflow.com/questions/1535564">related question</a>, I asked where to find the documentation for the C function "wait." This was an attempt to figure out return codes for the commands.getstatusoutput() module. Stackoverflow came through, but the documentation didn't help. Here's what puzzles me:</p> <pre><code>#!/usr/bin/python import commands goodcommand = 'ls /' badcommand = 'ls /fail' status, output = commands.getstatusoutput(goodcommand) print('Good command reported status of %s' % status) status, output = commands.getstatusoutput(badcommand) print('Bad command reported status of %s' % status) </code></pre> <p>When run on OS X (Leopard) I get the following output: (Which matches the documentation.)</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 256 </code></pre> <p>On OS X, doing an "ls /fail ; echo $?" gets the following output:</p> <pre><code>$ ls /fail ; echo $? ls: /fail: No such file or directory 1 </code></pre> <p>When run on Linux (Ubuntu Hardy) I get the following output:</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 512 </code></pre> <p>On Ubuntu, doing "ls /fail" gets a 2:</p> <pre><code>$ ls /fail ; echo $? ls: cannot access /fail: No such file or directory 2 </code></pre> <p>So Python appears to be multiplying status codes by 256. Huh? Is this documented somewhere?</p>
4
2009-10-08T04:43:50Z
1,535,703
<p>There is a set of functions in <code>os</code> module (<code>os.WIFCONTINUED</code>, <code>os.WIFSTOPPED</code>, <code>os.WTERMSIG</code>, <code>os.WCOREDUMP</code>, <code>os.WIFEXITED</code>, <code>os.WEXITSTATUS</code>, <code>os.WIFSIGNALED</code>, <code>os.WSTOPSIG</code>), which correspond to macros from <a href="http://linux.die.net/man/2/wait">wait(2)</a> manual. You should use them to interpret the status code.</p> <p>For example, to get the exit code you should use <code>os.WEXITSTATUS(status)</code></p> <p>A better idea would be to switch to <code>subprocess</code> module.</p>
8
2009-10-08T04:54:19Z
[ "python", "documentation", "subprocess", "command", "exit-code" ]
How to interpret status code in Python commands.getstatusoutput()
1,535,672
<p>In a <a href="http://stackoverflow.com/questions/1535564">related question</a>, I asked where to find the documentation for the C function "wait." This was an attempt to figure out return codes for the commands.getstatusoutput() module. Stackoverflow came through, but the documentation didn't help. Here's what puzzles me:</p> <pre><code>#!/usr/bin/python import commands goodcommand = 'ls /' badcommand = 'ls /fail' status, output = commands.getstatusoutput(goodcommand) print('Good command reported status of %s' % status) status, output = commands.getstatusoutput(badcommand) print('Bad command reported status of %s' % status) </code></pre> <p>When run on OS X (Leopard) I get the following output: (Which matches the documentation.)</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 256 </code></pre> <p>On OS X, doing an "ls /fail ; echo $?" gets the following output:</p> <pre><code>$ ls /fail ; echo $? ls: /fail: No such file or directory 1 </code></pre> <p>When run on Linux (Ubuntu Hardy) I get the following output:</p> <pre><code>$ python waitest.py Good command reported status of 0 Bad command reported status of 512 </code></pre> <p>On Ubuntu, doing "ls /fail" gets a 2:</p> <pre><code>$ ls /fail ; echo $? ls: cannot access /fail: No such file or directory 2 </code></pre> <p>So Python appears to be multiplying status codes by 256. Huh? Is this documented somewhere?</p>
4
2009-10-08T04:43:50Z
1,675,237
<p>I think the code detection is incorrect.</p> <p>"If a core file was produced, the high bit of the low byte is set." means 128.</p> <p>so I think the core line should be</p> <pre><code>print 'Core? : %s' % bool(status &amp; 128) </code></pre>
0
2009-11-04T17:04:50Z
[ "python", "documentation", "subprocess", "command", "exit-code" ]
Python not a standardized language?
1,535,702
<p>I stumbled upon this 'list of programming' languages and found that popular languages like Python are not standardized? Why is that, and what does 'Standardized' mean anyway?</p>
8
2009-10-08T04:54:18Z
1,535,714
<p>Standardized means there exists a specification for the language (a "standard"). Java, for example, has a specification. Perl 5 does not (the source code is the "standard") but Perl 6 will.</p> <p>See <a href="http://stackoverflow.com/questions/1094961/is-there-a-python-language-specification">Is there a Python language specification?</a></p>
2
2009-10-08T04:57:40Z
[ "php", "python", "standardized" ]
Python not a standardized language?
1,535,702
<p>I stumbled upon this 'list of programming' languages and found that popular languages like Python are not standardized? Why is that, and what does 'Standardized' mean anyway?</p>
8
2009-10-08T04:54:18Z
1,535,727
<p>"Standardized" means that the language has a formal, approved standard, generally written by ISO or ANSI or ECMA. Many modern open-source languages, like Python, Perl, and Ruby, are not formally standardized by an external body, and instead have a <em>de-facto</em> standard: whatever the original working implementation does.</p> <p>The benefits of standardizing a language are a) you know the language won't randomly change on you, b) if you want to write your own compiler/interpreter for the language, you have a very clear document that tells you what behavior everything should do, rather than having to test that behavior yourself in the original implementation. Because of this, standardized languages change slowly, and often have multiple major implementations.</p> <p>A language doesn't really have to be standardized to be useful. Most nonstandard languages won't just make random backwards-incompatable changes for no reason (and if they do, they take ten years to decide how to *cough*Perl6*cough*), and nonstandard languages can add cool new experimental features much faster (and more portably) than standardized languages.</p> <p>A few standardized languages:</p> <ul> <li>C</li> <li>C++</li> <li>Common Lisp</li> <li>Scheme (?)</li> <li>JavaScript (ECMAScript)</li> <li>C#</li> <li>Ruby</li> </ul> <p>Nonstandardized languages:</p> <ul> <li>Perl</li> <li>Python</li> <li>PHP</li> <li>Objective-C</li> </ul> <p>A full list is on <a href="http://en.wikipedia.org/wiki/Comparison_of_programming_languages" rel="nofollow">Wikipedia</a>.</p>
28
2009-10-08T05:04:44Z
[ "php", "python", "standardized" ]
Python not a standardized language?
1,535,702
<p>I stumbled upon this 'list of programming' languages and found that popular languages like Python are not standardized? Why is that, and what does 'Standardized' mean anyway?</p>
8
2009-10-08T04:54:18Z
1,537,045
<p>There are "standards" and there are "standards".</p> <p>Most folks mostly mean that a standard is passed by a standards-writing organization: ISO, ECMA, EIA, etc. Lawyers call these De Jure Standards. There's the force of law.</p> <p>Further, there are "De Facto Standards".</p> <p>Some folks, also, corrupt the word by adding "Industry Standard", or "<em>vendorname</em> Standard". This is just meaningless marketing noise. </p> <p>A De Facto Standard is something that's standardized in practice (because everyone does it and agrees they're doing it that way) but it is <em>not</em> backed by some standards organization.</p> <p>Python has a De Facto Standard, not a De Jure Standard.</p>
3
2009-10-08T10:51:13Z
[ "php", "python", "standardized" ]
Customizing time zones for Django users using geography
1,536,392
<p>I am working on a Django app that needs to report the local time relative to the user. I would prefer not ask the user to input the time zone directly because I have his address stored in the database. I am only considering American users. Since most states in the USA are in only one time zone it is possible to calculate the time zone based on the state information for most cases. I want to give a function the name of a state/geographic information and have it return the time offset from UTC of that state considering day light savings time.</p> <p>Is there a library that can do this for python?</p>
2
2009-10-08T08:22:34Z
1,536,426
<p>I am not sure such a library exists. Every state in the USA doesn't have only one time zone.</p> <p>Have a look here: <a href="http://en.wikipedia.org/wiki/List%5Fof%5FU.S.%5Fstates%5Fby%5Ftime%5Fzone" rel="nofollow">List of U.S. states by time zone</a></p> <p>Many states have more than one.</p> <p>I guess you could still use that list and pick the timezone that the majority of the state uses and then allow the users to customize theirs if it differs.</p>
3
2009-10-08T08:30:07Z
[ "python", "django", "timezone" ]
Customizing time zones for Django users using geography
1,536,392
<p>I am working on a Django app that needs to report the local time relative to the user. I would prefer not ask the user to input the time zone directly because I have his address stored in the database. I am only considering American users. Since most states in the USA are in only one time zone it is possible to calculate the time zone based on the state information for most cases. I want to give a function the name of a state/geographic information and have it return the time offset from UTC of that state considering day light savings time.</p> <p>Is there a library that can do this for python?</p>
2
2009-10-08T08:22:34Z
1,536,531
<p>I'm not sure how reliable it is, but the HTTP request - encapsulated in Django in the <code>request</code> object - has a <code>TZ</code> header which shows the client's time zone. </p> <pre><code>&gt;&gt;&gt; request.META['TZ'] 'Europe/London' </code></pre>
0
2009-10-08T08:54:43Z
[ "python", "django", "timezone" ]
Customizing time zones for Django users using geography
1,536,392
<p>I am working on a Django app that needs to report the local time relative to the user. I would prefer not ask the user to input the time zone directly because I have his address stored in the database. I am only considering American users. Since most states in the USA are in only one time zone it is possible to calculate the time zone based on the state information for most cases. I want to give a function the name of a state/geographic information and have it return the time offset from UTC of that state considering day light savings time.</p> <p>Is there a library that can do this for python?</p>
2
2009-10-08T08:22:34Z
1,537,346
<p>Like Andre Miller pointed out, time zones are not tied to state. You're probably better off using the zipcode, because a few cities cross timezone lines. </p> <p>There are a few databases you can purchase that that map zipcodes to time zones. Here's one I found that also includes the UTC shift and Daylight Savings:</p> <p><a href="http://www.zipcodedownload.com/Products/Product/Z5Commercial/Standard/Overview/" rel="nofollow">USA 5-digit Zipcode DB with time zone info.</a></p> <p>I haven't done the time zone thing before, but I've used this sort of database for lat/log information. The data <em>does</em> change, so plan on updating your database a few times a year. </p> <p>BTW, if anybody knows of a free database like this, please post: I think it would be really handy for the community.</p>
0
2009-10-08T11:52:16Z
[ "python", "django", "timezone" ]
Turbogears 2.0 with Python 2.6
1,536,437
<p>I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error:</p> <pre><code>File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in &lt;module&gt; load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 73, in run commands = get_commands() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 115, in get_ plugins = pluginlib.resolve_plugins(plugins) File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\pluginlib.py", line 81, in res pkg_resources.require(plugin) File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 626, in require File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 524, in resolve pkg_resources.DistributionNotFound: zope.sqlalchemy&gt;=0.4: Not Found for: City_Guide (did you run python setup.py develop?) </code></pre> <p>Now, according to the documentation on the main site, TurboGears 2.0 supports Python 2.6 in <a href="http://www.turbogears.org/2.0/docs/main/DownloadInstall.html#python" rel="nofollow">this page</a>:</p> <blockquote> <p>TurboGears works with any version of python between 2.4 and 2.6. The most widely deployed version of python at the moment of this writing is version 2.5. Both python 2.4 and python 2.6 require additional steps which will be covered in the appropriate sections.</p> </blockquote> <p>But they never mention those steps in the documentation.</p>
0
2009-10-08T08:32:23Z
1,536,482
<p>did you run python setup.py develop? (as the error message says)</p> <blockquote> <p>I was using virtualenv as recommended in the documentation, but the develop command installs the packages in the original python folder.</p> </blockquote> <p>Okay, that is the cause of your problems. I'm wondering about your comment "but the develop command installs..." The develop command of your web app shouldn't install anything. It's just meant to set up the database.</p> <p>Are you running this command <em>inside</em> the directory of your web app?</p>
1
2009-10-08T08:44:16Z
[ "python", "turbogears" ]
Turbogears 2.0 with Python 2.6
1,536,437
<p>I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error:</p> <pre><code>File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in &lt;module&gt; load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 73, in run commands = get_commands() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 115, in get_ plugins = pluginlib.resolve_plugins(plugins) File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\pluginlib.py", line 81, in res pkg_resources.require(plugin) File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 626, in require File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 524, in resolve pkg_resources.DistributionNotFound: zope.sqlalchemy&gt;=0.4: Not Found for: City_Guide (did you run python setup.py develop?) </code></pre> <p>Now, according to the documentation on the main site, TurboGears 2.0 supports Python 2.6 in <a href="http://www.turbogears.org/2.0/docs/main/DownloadInstall.html#python" rel="nofollow">this page</a>:</p> <blockquote> <p>TurboGears works with any version of python between 2.4 and 2.6. The most widely deployed version of python at the moment of this writing is version 2.5. Both python 2.4 and python 2.6 require additional steps which will be covered in the appropriate sections.</p> </blockquote> <p>But they never mention those steps in the documentation.</p>
0
2009-10-08T08:32:23Z
2,374,272
<p>I had the same problem. I was finally able to get it to work. I closed the command window. i opened a new commandwindow and activated the virtualenv by executing the appropriate activate.bat. Afterwards I reexecuted "setup.py develop" and finally i was able to start paster serve as documented in the Turbogears wiki.</p>
0
2010-03-03T19:23:29Z
[ "python", "turbogears" ]
Turbogears 2.0 with Python 2.6
1,536,437
<p>I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error:</p> <pre><code>File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in &lt;module&gt; load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 73, in run commands = get_commands() File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\command.py", line 115, in get_ plugins = pluginlib.resolve_plugins(plugins) File "D:\PythonProjects\tg2env\lib\site-packages\pastescript-1.7.3-py2.6.egg\paste\script\pluginlib.py", line 81, in res pkg_resources.require(plugin) File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 626, in require File "D:\PythonProjects\tg2env\lib\site-packages\setuptools-0.6c9-py2.6.egg\pkg_resources.py", line 524, in resolve pkg_resources.DistributionNotFound: zope.sqlalchemy&gt;=0.4: Not Found for: City_Guide (did you run python setup.py develop?) </code></pre> <p>Now, according to the documentation on the main site, TurboGears 2.0 supports Python 2.6 in <a href="http://www.turbogears.org/2.0/docs/main/DownloadInstall.html#python" rel="nofollow">this page</a>:</p> <blockquote> <p>TurboGears works with any version of python between 2.4 and 2.6. The most widely deployed version of python at the moment of this writing is version 2.5. Both python 2.4 and python 2.6 require additional steps which will be covered in the appropriate sections.</p> </blockquote> <p>But they never mention those steps in the documentation.</p>
0
2009-10-08T08:32:23Z
2,837,420
<p>The key is to run <strong>python</strong> setup.py development.ini. If you just run setup.py development.ini, it will use the installed python, and will not litter to your virtualenv</p>
0
2010-05-14T20:32:44Z
[ "python", "turbogears" ]
How to do email-confirmation after registration in Django?
1,536,766
<p>I am using Django's authentication system. Is there an easy way to do this?</p>
2
2009-10-08T09:54:50Z
1,536,774
<p>Have a look at James Bennett's <a href="http://bitbucket.org/ubernostrum/django-registration/wiki/Home" rel="nofollow">django-registration</a> project.</p>
8
2009-10-08T09:56:18Z
[ "python", "django" ]
Can't Delete Function Call
1,536,890
<p>This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today).</p> <p>Take this code:</p> <pre><code>List = ["hi","stack","over","flow","how","you","doing"] del List(len(List)-1) </code></pre> <p>Error:</p> <pre><code>SyntaxError: can't delete function call </code></pre> <p>I don't understand why you aren't allowed to delete an index of a list by referencing a call to a function? Do I just shut up and accept you can't do it or am I doing something fundamentally wrong?</p> <p>I apologise if there is an easy answer to this but either Google is getting less helpful or this is so blatantly obvious I need help.</p>
0
2009-10-08T10:19:21Z
1,536,903
<p>You are calling a function <code>List()</code> when you should be indexing a list, <code>List[]</code>.</p> <p>In Python, Round parenthesis, <code>()</code>, are used to call functions, while square brackets, <code>[]</code> are used to index lists and other sequences.</p> <p>Try:</p> <pre><code>del List[len(List) - 1] </code></pre> <p>or even better, use the fact that Python allows negative indexes, which count from the end:</p> <pre><code>del List[-1] </code></pre> <p>Also, you might want to make the list's name not so close to the built-in <code>list</code> type name, for clarity.</p>
5
2009-10-08T10:21:37Z
[ "python", "syntax-error" ]
Can't Delete Function Call
1,536,890
<p>This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today).</p> <p>Take this code:</p> <pre><code>List = ["hi","stack","over","flow","how","you","doing"] del List(len(List)-1) </code></pre> <p>Error:</p> <pre><code>SyntaxError: can't delete function call </code></pre> <p>I don't understand why you aren't allowed to delete an index of a list by referencing a call to a function? Do I just shut up and accept you can't do it or am I doing something fundamentally wrong?</p> <p>I apologise if there is an easy answer to this but either Google is getting less helpful or this is so blatantly obvious I need help.</p>
0
2009-10-08T10:19:21Z
1,536,920
<p>You meant to delete the last element of the list, not somehow call <code>List</code> as a function:</p> <pre><code>del List[len(List)-1] </code></pre> <p>Python's <code>del</code> statement must take specific forms like deleting a variable, list[element], or object.property. These forms can be nested deeply, but must be followed. It parallels the assignment statement -- you'll get a similar syntax error if you try to assign to a function call.</p> <p>Of course, what you <em>really</em> want in this case is</p> <pre><code>del List[-1] </code></pre> <p>which means the last element of the list, and is way more Pythonic.</p>
11
2009-10-08T10:23:16Z
[ "python", "syntax-error" ]
Can't Delete Function Call
1,536,890
<p>This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today).</p> <p>Take this code:</p> <pre><code>List = ["hi","stack","over","flow","how","you","doing"] del List(len(List)-1) </code></pre> <p>Error:</p> <pre><code>SyntaxError: can't delete function call </code></pre> <p>I don't understand why you aren't allowed to delete an index of a list by referencing a call to a function? Do I just shut up and accept you can't do it or am I doing something fundamentally wrong?</p> <p>I apologise if there is an easy answer to this but either Google is getting less helpful or this is so blatantly obvious I need help.</p>
0
2009-10-08T10:19:21Z
1,536,922
<p>You are allowed. However, you are using the wrong syntax. Correct syntax is:</p> <pre><code>del List[-1] </code></pre> <p>Notice that the "len(List) part is useless.</p>
1
2009-10-08T10:23:55Z
[ "python", "syntax-error" ]
Building universal binaries on Mac - Forcing single compiler child process
1,536,897
<p>Cheers,</p> <p>at company, we're creating a port of our games, and we need to compile <a href="http://www.pythonogre.com/" rel="nofollow">PythonOgre</a>, a wrapper of Ogre3d for Python. This is an enormous chunk of code, particularly the generated wrapper code. We have a Mac Mini with 1GB RAM.</p> <p>We've built i386 version. Since we have only 1GB of RAM, we've forced the build system to use only one core; second process running at the same time took a nice trip into the virtual memory.</p> <p>Now, we need to produce universal binaries, because publisher insists on supporting PPC. To facilitate building of universal binaries, we've modified the <code>CFLAGS</code> and <code>CXXFLAGS</code> to include <code>-arch i386 -arch ppc</code> when compiling wrapper code (Ogre3d itself already seems to be an universal binary).</p> <p>However, Apple has decided to use both cores when creating universal binary, and this has caused the system to roll over and die. (Well, crawl at 0.9-1.4% CPU usage, anyways.) While ordinarily we would appreciate this, on a 1GB Mac Mini, this completely blocks our development.</p> <p>Aside from getting a new build machine, giving up on PPC support and producing a PPC-only build, the only recourse we have is to block GCC's spawning of second simultaneous process.</p> <p>How would we go about that?</p>
1
2009-10-08T10:20:48Z
1,537,300
<p>I've checked the source of Apple's GCC driver (the one that supports those <code>-arch</code> options and runs the children processes), and there's no option or environment variable that you can choose.</p> <p>The only options I see left to you are:</p> <ul> <li>download the Apple driver (e.g. from <a href="http://r.research.att.com/tools/" rel="nofollow">there</a>; end of the page) and modify the file <code>driverdriver.c</code> so that processes are launched sequentially (rather than in parallel)</li> <li>do separate i386 and powerpc builds, and join the final build objects (executables, shared libraries, etc.) using <code>lipo</code></li> </ul> <p>I hope this helps!</p>
2
2009-10-08T11:40:43Z
[ "python", "osx", "gcc", "multicore" ]
Building universal binaries on Mac - Forcing single compiler child process
1,536,897
<p>Cheers,</p> <p>at company, we're creating a port of our games, and we need to compile <a href="http://www.pythonogre.com/" rel="nofollow">PythonOgre</a>, a wrapper of Ogre3d for Python. This is an enormous chunk of code, particularly the generated wrapper code. We have a Mac Mini with 1GB RAM.</p> <p>We've built i386 version. Since we have only 1GB of RAM, we've forced the build system to use only one core; second process running at the same time took a nice trip into the virtual memory.</p> <p>Now, we need to produce universal binaries, because publisher insists on supporting PPC. To facilitate building of universal binaries, we've modified the <code>CFLAGS</code> and <code>CXXFLAGS</code> to include <code>-arch i386 -arch ppc</code> when compiling wrapper code (Ogre3d itself already seems to be an universal binary).</p> <p>However, Apple has decided to use both cores when creating universal binary, and this has caused the system to roll over and die. (Well, crawl at 0.9-1.4% CPU usage, anyways.) While ordinarily we would appreciate this, on a 1GB Mac Mini, this completely blocks our development.</p> <p>Aside from getting a new build machine, giving up on PPC support and producing a PPC-only build, the only recourse we have is to block GCC's spawning of second simultaneous process.</p> <p>How would we go about that?</p>
1
2009-10-08T10:20:48Z
1,541,551
<p>Will just turning off one core do? Apparently, installing the Apple Developer Tools (XCode et al.) gives you a Processor system preference pane, allowing you to turn off one core. I was trying to test this, but the XCode install failed for some reason...</p> <p>EDIT: I know this was a while ago, but I just thought of something. Why not build with -march=i386 and -march=ppc separately and then combine the binaries using lipo?</p>
1
2009-10-09T02:39:45Z
[ "python", "osx", "gcc", "multicore" ]
Creating Title / Slug based on PK ID
1,537,149
<p>What would be the generic way to create record title and slub based on the ID? I am working with django-photologue here. I want to save a record with title and slug based on the PK. The generic problem is that I can't get the PK until the record is saved into database. On the other side, I can't save it without title and slug. </p> <p>What common solution is that that kind of problem?</p>
1
2009-10-08T11:14:28Z
1,537,172
<p>Normally you don't use the primary key at all. If your concern is just to automatically generate unique slugs (which is the only reason I can see to do what you're trying to do), then you want an <code>AutoSlugField</code>, which creates a unique slug by increasing an appended number on the slug until it is unique.</p> <p>There's an implementation of <code>AutoSlugField</code> which is part of <a href="http://code.google.com/p/django-command-extensions/wiki/FieldExtensions" rel="nofollow">django-command-extensions</a>.</p>
1
2009-10-08T11:18:52Z
[ "python", "django", "django-profiles" ]
Creating Title / Slug based on PK ID
1,537,149
<p>What would be the generic way to create record title and slub based on the ID? I am working with django-photologue here. I want to save a record with title and slug based on the PK. The generic problem is that I can't get the PK until the record is saved into database. On the other side, I can't save it without title and slug. </p> <p>What common solution is that that kind of problem?</p>
1
2009-10-08T11:14:28Z
1,537,448
<p>To name the file based on record ID you have several options:</p> <p>a) Try to predict ID:</p> <pre><code>max_pk = self.__class__.objects.aggregate(max_pk=Max('pk'))['max_pk'] or 0 predicted_id = max_pk+1 </code></pre> <p>b) Rename file in post_save when ID is known.</p> <p>You can also use md5 hash or random strings for generating unique file names.</p> <p>Btw, there is separate <a href="http://bitbucket.org/neithere/django-autoslug/" rel="nofollow">django-autoslug</a> app.</p>
0
2009-10-08T12:15:39Z
[ "python", "django", "django-profiles" ]
Creating Title / Slug based on PK ID
1,537,149
<p>What would be the generic way to create record title and slub based on the ID? I am working with django-photologue here. I want to save a record with title and slug based on the PK. The generic problem is that I can't get the PK until the record is saved into database. On the other side, I can't save it without title and slug. </p> <p>What common solution is that that kind of problem?</p>
1
2009-10-08T11:14:28Z
1,537,522
<p>If you URIs are supposed to look like <code>"example.com/${obj.id}-${sluggify( obj.title )}"</code> then <em>generate these uri when you use them</em>. This uri contains no data that's not in the DB already, so don't add it again. The slug's sole purpose is making url's look nicer to people and search engines.</p> <p>Take Stackoverflow as an example: <a href="http://stackoverflow.com/questions/1537149/slugs-have-no-meaning-and-can-be-anything">http://stackoverflow.com/questions/1537149/slugs-have-no-meaning-and-can-be-anything</a> </p> <p>If you want to select by the slug only, it has to be a Primary Key, unique and immutable. You should be aware that having another PK, the usual <code>id</code> column, would be unneeded.</p> <p>I don't say slugs are bad, nor that saving slugs is always bad. There are many valid reasons to save them in the database, but then you need to <em>think</em> about what you're doing. </p> <p>Selecting data by their PK (and ignoring the slug) on the other hand requires no thinking, so that should be the default way to go.</p>
1
2009-10-08T12:34:04Z
[ "python", "django", "django-profiles" ]
Reading from sockets and download speed
1,537,161
<p>Just for fun, I develop a download manager and I'd like to know if reading a large stack of data (i.e. 80 or 100KB) from a socket over the net makes the download speed higher, instead of reading 4KB for each loop iteration?</p> <p>(My average download speed is 200KBPS when I download a file with firefox for example)</p> <p>Thanks, Nir Tayeb.</p>
0
2009-10-08T11:16:47Z
1,537,199
<p>The answer is <strong>NO</strong>.</p> <p>your network transfer rate (200kbps) indicates that buffering 4k or 8k or 200k will hardly make a difference. The time spent between reads is too small. The bottleneck seems to be your transfer rate anyway.</p> <p>Let's try with a <a href="http://itc.conversationsnetwork.org/shows/detail4253.html" rel="nofollow">stackoverflow 30.9MB mp3 podcast</a>:</p> <blockquote> <p><strong><em>NOTE</strong>: This is a unreliable hack whose results can be affected by a lot of factors - useful for demonstration purposes only)</em></p> </blockquote> <pre><code>import urllib2 import time def report(start, size, text): total = time.time() - start print "%s reading took %d seconds, transfer rate %.2f KBPS" % ( text, total, (size / 1024.0) / total) start = time.time() url = ('http://itc.conversationsnetwork.org/audio/download/' 'ITC.SO-Episode69-2009.09.29.mp3') f = urllib2.urlopen(url) start = time.time() data = f.read() # read all data in a single, blocking operation report(start, len(data), 'All data') f.close() f = urllib2.urlopen(url) start = time.time() while True: chunk = f.read(4096) # read a chunk if not chunk: break report(start, len(data), 'Chunked') f.close() </code></pre> <p>The results in my system:</p> <pre><code>All data reading took 137 seconds, transfer rate 230.46 KBPS Chunked reading took 137 seconds, transfer rate 230.49 KBPS </code></pre> <p>So for my system, 2 megabit connection, file size, server chosen, it is not much of a difference if I used chunked reading or not.</p>
2
2009-10-08T11:24:28Z
[ "python", "sockets" ]
Variables inside and outside of a class __init__() function
1,537,202
<p>I'm trying to understand, is there any difference at all between these classes besides the name? Does it make any difference if I use or don't use the __init__() function in declaring the variable "value"?</p> <pre><code>class WithClass (): def __init__(self): self.value = "Bob" def my_func(self): print(self.value) class WithoutClass (): value = "Bob" def my_func(self): print(self.value) </code></pre> <p>My main worry is that I'll be using it one way when that'll cause me problems further down the road (currently I use the init call).</p>
73
2009-10-08T11:25:27Z
1,537,226
<p>Variable set outside <code>__init__</code> belong to the class. They're shared by all instances. </p> <p>Variables created inside <code>__init__</code> (and all other method functions) and prefaced with <code>self.</code> belong to the object instance. </p>
87
2009-10-08T11:29:15Z
[ "python" ]
Variables inside and outside of a class __init__() function
1,537,202
<p>I'm trying to understand, is there any difference at all between these classes besides the name? Does it make any difference if I use or don't use the __init__() function in declaring the variable "value"?</p> <pre><code>class WithClass (): def __init__(self): self.value = "Bob" def my_func(self): print(self.value) class WithoutClass (): value = "Bob" def my_func(self): print(self.value) </code></pre> <p>My main worry is that I'll be using it one way when that'll cause me problems further down the road (currently I use the init call).</p>
73
2009-10-08T11:25:27Z
15,247,457
<p>further to S.Lott's reply, class variables get passed to metaclass <strong>new</strong> method and can be accessed through the dictionary when a metaclass is defined. So, class variables can be accessed even before classes are created and instantiated.</p> <p>for example:</p> <pre><code>class meta(type): def __new__(cls,name,bases,dicto): # two chars missing in original of next line ... if dicto['class_var'] == 'A': print 'There' class proxyclass(object): class_var = 'A' __metaclass__ = meta ... ... </code></pre>
3
2013-03-06T12:32:06Z
[ "python" ]
Variables inside and outside of a class __init__() function
1,537,202
<p>I'm trying to understand, is there any difference at all between these classes besides the name? Does it make any difference if I use or don't use the __init__() function in declaring the variable "value"?</p> <pre><code>class WithClass (): def __init__(self): self.value = "Bob" def my_func(self): print(self.value) class WithoutClass (): value = "Bob" def my_func(self): print(self.value) </code></pre> <p>My main worry is that I'll be using it one way when that'll cause me problems further down the road (currently I use the init call).</p>
73
2009-10-08T11:25:27Z
26,529,574
<p><strong>Without Self</strong></p> <p>Create some objects:</p> <pre><code>class foo(object): x = 'original class' c1, c2 = foo(), foo() </code></pre> <p>I can change the c1 instance, and it will not affect the c2 instance:</p> <pre><code>c1.x = 'changed instance' c2.x &gt;&gt;&gt; 'original class' </code></pre> <p>But if I change the foo class, all instances of that class will be changed as well:</p> <pre><code>foo.x = 'changed class' c2.x &gt;&gt;&gt; 'changed class' </code></pre> <p>Please note how Python scoping works here:</p> <pre><code>c1.x &gt;&gt;&gt; 'changed instance' </code></pre> <p><strong>With Self</strong></p> <p>Changing the class does not affect the instances:</p> <pre><code>class foo(object): def __init__(self): self.x = 'original self' c1 = foo() foo.x = 'changed class' c1.x &gt;&gt;&gt; 'original self' </code></pre>
27
2014-10-23T13:46:36Z
[ "python" ]
What do I need to know/learn for automated python deployment?
1,537,298
<p>I'm starting a new webapp project in Python to get into the Agile mind-set and I'd like to do things "properly" with regards to deployment. However, I'm finding the whole virtualenv/fabric/zc.buildout/etc stuff a little confusing - I'm used to just FTP'ing PHP files to a server and pointing a webserver at it.</p> <p>After deployment the server set-up would look something like:<br /> <code>Nginx --proxy-to--&gt; WSGI Webserver (Spawning) --&gt; WSGI Middleware --&gt; WSGI App (probably MNML or similar)</code><br /> with the python webserver being managed by supervisord.</p> <p>What sort of deployment set-up/packages/apps should I be looking into? And is there a specific directory structure I need to stick to with my app to ease deployment?</p>
2
2009-10-08T11:40:12Z
1,537,335
<p>Your deployment story depends on your app. Are you using Django? Then the <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/" rel="nofollow">Apache + <code>mod_wsgi</code> deployment docs</a> make for a good starting point. Then you can google around for more detail, such as this <a href="http://lincolnloop.com/blog/2009/sep/22/easy-fabric-deployment-part-1-gitmercurial-and-ssh/" rel="nofollow">2-part</a> <a href="http://lincolnloop.com/blog/2009/oct/7/easy-fabric-deployment-part-2/" rel="nofollow">series</a> using <code>pip</code>, <code>virtualenv</code>, <code>git</code>, and <code>fabric</code>.</p> <p>Really, <code>fabric</code>, <code>virtualenv</code>, and all those other tools are designed to make it easier to maintain and automate your deployment. Initially, the steps from the documentation are probably enough. After you get a feel for how things work, you can revisit to improve your process.</p>
4
2009-10-08T11:49:33Z
[ "python", "deployment", "virtualenv" ]
What do I need to know/learn for automated python deployment?
1,537,298
<p>I'm starting a new webapp project in Python to get into the Agile mind-set and I'd like to do things "properly" with regards to deployment. However, I'm finding the whole virtualenv/fabric/zc.buildout/etc stuff a little confusing - I'm used to just FTP'ing PHP files to a server and pointing a webserver at it.</p> <p>After deployment the server set-up would look something like:<br /> <code>Nginx --proxy-to--&gt; WSGI Webserver (Spawning) --&gt; WSGI Middleware --&gt; WSGI App (probably MNML or similar)</code><br /> with the python webserver being managed by supervisord.</p> <p>What sort of deployment set-up/packages/apps should I be looking into? And is there a specific directory structure I need to stick to with my app to ease deployment?</p>
2
2009-10-08T11:40:12Z
1,537,337
<p>I've heard good things about <a href="http://docs.fabfile.org/0.9/" rel="nofollow">Fabric</a>:</p> <blockquote> <p>Fabric is a Python library and command-line tool designed to streamline deploying applications or performing system administration tasks via the SSH protocol. It provides tools for running arbitrary shell commands (either as a normal login user, or via <code>sudo</code>), uploading and downloading files, and so forth.</p> </blockquote>
2
2009-10-08T11:49:55Z
[ "python", "deployment", "virtualenv" ]
What do I need to know/learn for automated python deployment?
1,537,298
<p>I'm starting a new webapp project in Python to get into the Agile mind-set and I'd like to do things "properly" with regards to deployment. However, I'm finding the whole virtualenv/fabric/zc.buildout/etc stuff a little confusing - I'm used to just FTP'ing PHP files to a server and pointing a webserver at it.</p> <p>After deployment the server set-up would look something like:<br /> <code>Nginx --proxy-to--&gt; WSGI Webserver (Spawning) --&gt; WSGI Middleware --&gt; WSGI App (probably MNML or similar)</code><br /> with the python webserver being managed by supervisord.</p> <p>What sort of deployment set-up/packages/apps should I be looking into? And is there a specific directory structure I need to stick to with my app to ease deployment?</p>
2
2009-10-08T11:40:12Z
1,537,585
<p>You already mentioned buildout, and it's all you need. Google for example buildouts for the different parts. Takes a while to set it up the first time, but then you can reuse the setup between different projects too.</p> <p>Let supervisord start everything, not just the python server. Then start supervisord at reboot either fron cron or init.d.</p>
2
2009-10-08T12:48:45Z
[ "python", "deployment", "virtualenv" ]
Identifying twitter user's longitude and latitude
1,537,303
<p>As per my requirement in need to search twitter and display user's location on map. Can anyone help me identifying longitude and latitude from search api result?</p>
1
2009-10-08T11:41:16Z
1,537,382
<p>Last time I looked it didn't include it officially, unless the specific client (such as an iphone client) specifically updated your location to lat+long coordinates.</p> <p>When I did something similar I passed the Twitter RSS output through an rss <a href="http://en.wikipedia.org/wiki/Geotagging" rel="nofollow">geotagging</a> service, then used the output from that to map. It worked, but 99% of the tweets were just city centres, so it was pretty pointless :-(</p>
1
2009-10-08T12:01:35Z
[ "c#", "asp.net", "python", "twitter" ]
Identifying twitter user's longitude and latitude
1,537,303
<p>As per my requirement in need to search twitter and display user's location on map. Can anyone help me identifying longitude and latitude from search api result?</p>
1
2009-10-08T11:41:16Z
1,537,418
<p>Twitter hasn't released their new geocoding API yet. Twitter's API Documentation is available here.</p> <p><a href="http://apiwiki.twitter.com/Twitter-API-Documentation" rel="nofollow">http://apiwiki.twitter.com/Twitter-API-Documentation</a></p> <p>As you can see, most of the current API methods return an empty "geo" tag. Once Twitter has rolled out their geo implementation, this tag will be populated.</p>
1
2009-10-08T12:09:31Z
[ "c#", "asp.net", "python", "twitter" ]
Identifying twitter user's longitude and latitude
1,537,303
<p>As per my requirement in need to search twitter and display user's location on map. Can anyone help me identifying longitude and latitude from search api result?</p>
1
2009-10-08T11:41:16Z
1,537,883
<p>You'd probably be best to see what "location" the user has set then use a geo-coding api to try and convert that location into lat/lng.</p> <p>e.g. use <a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users%C2%A0show" rel="nofollow">http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users%C2%A0show</a> to find out the user's location, then use google's geocoding API (<a href="http://code.google.com/apis/maps/documentation/geocoding/" rel="nofollow">http://code.google.com/apis/maps/documentation/geocoding/</a>) to do the rest.</p> <p>Also you would probably want to do some pre-processing on the location to see if it's already a lat/lng pair (as some users update their location in this manner).</p>
0
2009-10-08T13:43:05Z
[ "c#", "asp.net", "python", "twitter" ]
SimpleParse non-deterministic grammar until runtime
1,537,708
<p>I'm working on a basic networking protocol in Python, which should be able to transfer both ASCII strings (read: EOL-terminated) and binary data. For the latter to be possible, I chose to create the grammar such that it contains the number of bytes to come which are going to be binary.</p> <p>For SimpleParse, the grammar would look like this [1] so far:</p> <pre><code>EOL := [\n] IDENTIFIER := [a-zA-Z0-9_-]+ SIZE_INTEGER := [1-9]*[0-9]+ ASCII_VALUE := [^\n\0]+, EOL BINARY_VALUE := .*+ value := (ASCII_VALUE/BINARY_VALUE) eol_attribute := IDENTIFIER, ':', value binary_attribute := IDENTIFIER, [\t], SIZE_INTEGER, ':', value attributes := (eol_attribute/binary_attribute)+ command := IDENTIFIER, EOL command := IDENTIFIER, '{', attributes, '}' </code></pre> <p>The problem is I don't know how to instruct SimpleParse that the following is going to be a chuck of binary data of SIZE_INTEGER bytes <strong>at runtime</strong>.</p> <p>The cause for this is the definition of the terminal BINARY_VALUE which fulfills my needs as it is now, so it cannot be changed.</p> <p>Thanks</p> <p><strong>Edit</strong></p> <p>I suppose the solution would be telling it to stop when it matches the production binary_attribute and let me populate the AST node manually (via socket.recv()), but <strong>how to do that?</strong></p> <p><strong>Edit 2</strong></p> <p>Base64-encoding or similar is not an option.</p> <p>[1] I have't tested it, so I don't know if it practically works, it's only for you to get an idea</p>
1
2009-10-08T13:11:07Z
1,599,823
<p>If the grammar is as simple as the one you quoted, then perhaps using a parser generator is overkill? You might find that rolling your own recursive parser by hand is simpler and quicker.</p>
4
2009-10-21T09:59:28Z
[ "python", "parsing", "text-parsing" ]
SimpleParse non-deterministic grammar until runtime
1,537,708
<p>I'm working on a basic networking protocol in Python, which should be able to transfer both ASCII strings (read: EOL-terminated) and binary data. For the latter to be possible, I chose to create the grammar such that it contains the number of bytes to come which are going to be binary.</p> <p>For SimpleParse, the grammar would look like this [1] so far:</p> <pre><code>EOL := [\n] IDENTIFIER := [a-zA-Z0-9_-]+ SIZE_INTEGER := [1-9]*[0-9]+ ASCII_VALUE := [^\n\0]+, EOL BINARY_VALUE := .*+ value := (ASCII_VALUE/BINARY_VALUE) eol_attribute := IDENTIFIER, ':', value binary_attribute := IDENTIFIER, [\t], SIZE_INTEGER, ':', value attributes := (eol_attribute/binary_attribute)+ command := IDENTIFIER, EOL command := IDENTIFIER, '{', attributes, '}' </code></pre> <p>The problem is I don't know how to instruct SimpleParse that the following is going to be a chuck of binary data of SIZE_INTEGER bytes <strong>at runtime</strong>.</p> <p>The cause for this is the definition of the terminal BINARY_VALUE which fulfills my needs as it is now, so it cannot be changed.</p> <p>Thanks</p> <p><strong>Edit</strong></p> <p>I suppose the solution would be telling it to stop when it matches the production binary_attribute and let me populate the AST node manually (via socket.recv()), but <strong>how to do that?</strong></p> <p><strong>Edit 2</strong></p> <p>Base64-encoding or similar is not an option.</p> <p>[1] I have't tested it, so I don't know if it practically works, it's only for you to get an idea</p>
1
2009-10-08T13:11:07Z
1,617,131
<p>I strongly recommend you consider using the <a href="http://construct.wikispaces.com/tutorial" rel="nofollow">construct</a> library for parsing the binary data. It also has support for text (ASCII), so when it detects text you can pass that to your SimpleParse-based parser, but the binary data will be parsed with construct. It's very convenient and powerful.</p>
0
2009-10-24T06:11:01Z
[ "python", "parsing", "text-parsing" ]