title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Namespace Specification In Absence of Ambuguity
| 539,578
|
<p>Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like <code>using namespace x</code> in C++, or <code>from x import *</code> in Python. However, I can't understand the rationale behind not wanting the language to just "do the right thing" when only one accessible namespace contains a given identifier and no ambiguity exists. To me it's just unnecessary verbosity and a violation of DRY, since you're being forced to specify something the compiler already knows.</p>
<p>For example:</p>
<pre><code>import foo # Contains someFunction().
someFunction() # imported from foo. No ambiguity. Works.
</code></pre>
<p>Vs.</p>
<pre><code>import foo # Contains someFunction()
import bar # Contains someFunction() also.
# foo.someFunction or bar.someFunction? Should be an error only because
# ambiguity exists.
someFunction()
</code></pre>
| 0
|
2009-02-12T00:56:34Z
| 540,137
|
<p>Interesting question. In the case of C++, as I see it, provided the compiler flagged an error as soon as there was a conflict, the only problem this could cause would be:</p>
<p><strong>Auto-lookup of all C++ namespaces would remove the ability to hide the names of internal parts of library code.</strong></p>
<p>Library code often contains parts (types, functions, global variables) that are never intended to be visible to the "outside world." C++ has unnamed namespaces for exactly this reason -- to avoid "internal parts" clogging up the global namespace, even when those library namespaces are explicitly imported with <code>using namespace xyz;</code>.</p>
<p>Example: Suppose C++ <em>did</em> do auto-lookup, and a particular implementation of the C++ Standard Library contained an internal helper function, <code>std::helper_func()</code>. Suppose a user Joe develops an application containing a function <code>joe::helper_func()</code> using a <em>different</em> library implementation that does not contain <code>std::helper_func()</code>, and calls his own method using unqualified calls to <code>helper_func()</code>. Now Joe's code will compile fine in his environment, but any other user who tries to compile that code using the first library implementation will hit compiler error messages. So the first thing required to make Joe's code portable is to either insert the appropriate <code>using</code> declarations/directives or use fully qualified identifiers. In other words, auto-lookup buys nothing for portable code.</p>
<p>Admittedly, this doesn't seem like a problem that's likely to come up very often. But since typing explicit <code>using</code> declarations/directives (e.g. <code>using namespace std;</code>) is not a big deal for most people, solves this problem completely, and would be required for portable development anyway, using them (heh) seems like a sensible way to do things.</p>
<p><strong>NOTE:</strong> As Klaim pointed out, you would <strong>never in any circumstances</strong> want to rely on auto-lookup inside a header file, as this would immediately prevent your module from being used at the same time as any module containing a conflicting name. (This is just a logical extension of why you don't do <code>using namespace xyz;</code> inside headers in C++ as it stands.)</p>
| 0
|
2009-02-12T05:15:26Z
|
[
"c++",
"python",
"namespaces",
"language-design"
] |
Obtaining all possible states of an object for a NP-Complete(?) problem in Python
| 539,676
|
<p>Not sure that the example (nor the actual usecase) qualifies as NP-Complete, but I'm wondering about the most Pythonic way to do the below assuming that this was the algorithm available.</p>
<p>Say you have :</p>
<pre><code>class Person:
def __init__(self):
self.status='unknown'
def set(self,value):
if value:
self.status='happy'
else :
self.status='sad'
... blah . Maybe it's got their names or where they live or whatev.
</code></pre>
<p>and some operation that requires a group of Persons. (The key value is here whether the Person is happy or sad.)</p>
<p>Hence, given PersonA, PersonB, PersonC, PersonD - I'd like to end up a list of the possible 2**4 combinations of sad and happy Persons. i.e.</p>
<pre><code>[
[ PersonA.set(true), PersonB.set(true), PersonC.set(true), PersonD.set(true)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(true), PersonD.set(false)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(false), PersonD.set(true)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(false), PersonD.set(false)],
etc..
</code></pre>
<p>Is there a good Pythonic way of doing this? I was thinking about list comprehensions (and modifying the object so that you could call it and get returned two objects, true and false), but the comprehension formats I've seen would require me to know the number of Persons in advance. I'd like to do this independent of the number of persons.</p>
<p>EDIT : Assume that whatever that operation that I was going to run on this is part of a larger problem set - we need to test out all values of Person for a given set in order to solve our problem. (i.e. I know this doesn't look NP-complete right now =) )
any ideas?</p>
<p>Thanks!</p>
| 0
|
2009-02-12T01:45:41Z
| 539,695
|
<p>I think this could do it:</p>
<pre><code>l = list()
for i in xrange(2 ** n):
# create the list of n people
sublist = [None] * n
for j in xrange(n):
sublist[j] = Person()
sublist[j].set(i & (1 << j))
l.append(sublist)
</code></pre>
<p>Note that if you wrote <code>Person</code> so that its constructor accepted the value, or such that the <code>set</code> method returned the person itself (but that's a little weird in Python), you could use a list comprehension. With the constructor way:</p>
<pre><code>l = [ [Person(i & (1 << j)) for j in xrange(n)] for i in xrange(2 ** n)]
</code></pre>
<p>The runtime of the solution is <code>O(n 2**n)</code> as you can tell by looking at the loops, but it's not really a "problem" (i.e. a question with a yes/no answer) so you can't really call it NP-complete. See <a href="http://stackoverflow.com/questions/210829/what-is-an-np-complete-problem">http://stackoverflow.com/questions/210829/what-is-an-np-complete-problem</a> for more information on that front.</p>
| 2
|
2009-02-12T01:53:54Z
|
[
"iteration",
"python",
"combinatorics"
] |
Obtaining all possible states of an object for a NP-Complete(?) problem in Python
| 539,676
|
<p>Not sure that the example (nor the actual usecase) qualifies as NP-Complete, but I'm wondering about the most Pythonic way to do the below assuming that this was the algorithm available.</p>
<p>Say you have :</p>
<pre><code>class Person:
def __init__(self):
self.status='unknown'
def set(self,value):
if value:
self.status='happy'
else :
self.status='sad'
... blah . Maybe it's got their names or where they live or whatev.
</code></pre>
<p>and some operation that requires a group of Persons. (The key value is here whether the Person is happy or sad.)</p>
<p>Hence, given PersonA, PersonB, PersonC, PersonD - I'd like to end up a list of the possible 2**4 combinations of sad and happy Persons. i.e.</p>
<pre><code>[
[ PersonA.set(true), PersonB.set(true), PersonC.set(true), PersonD.set(true)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(true), PersonD.set(false)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(false), PersonD.set(true)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(false), PersonD.set(false)],
etc..
</code></pre>
<p>Is there a good Pythonic way of doing this? I was thinking about list comprehensions (and modifying the object so that you could call it and get returned two objects, true and false), but the comprehension formats I've seen would require me to know the number of Persons in advance. I'd like to do this independent of the number of persons.</p>
<p>EDIT : Assume that whatever that operation that I was going to run on this is part of a larger problem set - we need to test out all values of Person for a given set in order to solve our problem. (i.e. I know this doesn't look NP-complete right now =) )
any ideas?</p>
<p>Thanks!</p>
| 0
|
2009-02-12T01:45:41Z
| 539,831
|
<p>You can use a cartesian product to get all possible combinations of people and states. Requires Python 2.6+</p>
<pre><code>import itertools
people = [person_a,person_b,person_c]
states = [True,False]
all_people_and_states = itertools.product(people,states)
</code></pre>
<p>The variable *all_people_and_states* contains a list of tuples (x,y) where x is a person and y is either True or False. It will contain all possible pairings of people and states.</p>
| 1
|
2009-02-12T03:06:23Z
|
[
"iteration",
"python",
"combinatorics"
] |
Obtaining all possible states of an object for a NP-Complete(?) problem in Python
| 539,676
|
<p>Not sure that the example (nor the actual usecase) qualifies as NP-Complete, but I'm wondering about the most Pythonic way to do the below assuming that this was the algorithm available.</p>
<p>Say you have :</p>
<pre><code>class Person:
def __init__(self):
self.status='unknown'
def set(self,value):
if value:
self.status='happy'
else :
self.status='sad'
... blah . Maybe it's got their names or where they live or whatev.
</code></pre>
<p>and some operation that requires a group of Persons. (The key value is here whether the Person is happy or sad.)</p>
<p>Hence, given PersonA, PersonB, PersonC, PersonD - I'd like to end up a list of the possible 2**4 combinations of sad and happy Persons. i.e.</p>
<pre><code>[
[ PersonA.set(true), PersonB.set(true), PersonC.set(true), PersonD.set(true)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(true), PersonD.set(false)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(false), PersonD.set(true)],
[ PersonA.set(true), PersonB.set(true), PersonC.set(false), PersonD.set(false)],
etc..
</code></pre>
<p>Is there a good Pythonic way of doing this? I was thinking about list comprehensions (and modifying the object so that you could call it and get returned two objects, true and false), but the comprehension formats I've seen would require me to know the number of Persons in advance. I'd like to do this independent of the number of persons.</p>
<p>EDIT : Assume that whatever that operation that I was going to run on this is part of a larger problem set - we need to test out all values of Person for a given set in order to solve our problem. (i.e. I know this doesn't look NP-complete right now =) )
any ideas?</p>
<p>Thanks!</p>
| 0
|
2009-02-12T01:45:41Z
| 548,358
|
<p>According to what you've stated in your problem, you're right -- you do need <code>itertools.product</code>, but not exactly the way you've stated.</p>
<pre><code>import itertools
truth_values = itertools.product((True, False), repeat = 4)
people = (person_a, person_b, person_c, person_d)
all_people_and_states = [[person(truth) for person, truth in zip(people, combination)] for combination in truth_values]
</code></pre>
<p>That should be more along the lines of what you mentioned in your question.</p>
| 1
|
2009-02-14T02:23:09Z
|
[
"iteration",
"python",
"combinatorics"
] |
Custom django widget - decompress() arg not populated
| 539,899
|
<p>As an exercise I am trying to create a custom django widget for a 24 hour clock. The widget will is a MultiWidget - a select box for each field.</p>
<p>I am trying to follow docs online (kinda sparse) and looking at the Pro Django book, but I can't seem to figure it out. Am I on the right track? I can save my data from the form, but when I prepopulate the form, the form doesn't have the previous values. </p>
<p>It seems the issue is that the decompress() methods 'value' argument is always empty, so I have nothing to interpret.</p>
<pre><code>from django.forms import widgets
import datetime
class MilitaryTimeWidget(widgets.MultiWidget):
"""
A widget that displays 24 hours time selection.
"""
def __init__(self, attrs=None):
hours = [ (i, "%02d" %(i)) for i in range(0, 24) ]
minutes = [ (i, "%02d" %(i)) for i in range(0, 60) ]
_widgets = (
widgets.Select(attrs=attrs, choices=hours),
widgets.Select(attrs=attrs, choices=minutes),
)
super(MilitaryTimeWidget, self).__init__(_widgets, attrs)
def decompress(self, value):
print "******** %s" %value
if value:
return [int(value.hour), int(value.minute)]
return [None, None]
def value_from_datadict(self, data, files, name):
hour = data.get("%s_0" %name, None)
minute = data.get("%s_1" %name, None)
if hour and minute:
hour = int(hour)
minute = int(minute)
return datetime.time(hour=hour, minute=minute)
return None
</code></pre>
<p>In my form, I am calling the widget like:</p>
<pre><code>arrival_time = forms.TimeField(label="Arrival Time", required=False, widget=MilitaryTimeWidget())
</code></pre>
| 3
|
2009-02-12T03:30:40Z
| 540,678
|
<p>I can't reproduce the problem:</p>
<pre><code>>>> class MyForm(forms.Form):
... t = forms.TimeField(widget=MilitaryTimeWidget())
...
>>> print MyForm(data={'t_0': '13', 't_1': '34'})
******** 13:34:00
<tr><th><label for="id_t_0">T:</label></th><td><select name="t_0" id="id_t_0">
<option value="0">00</option>
[...]
<option value="13" selected="selected">13</option>
[...]
<option value="23">23</option>
</select><select name="t_1" id="id_t_1">
<option value="0">00</option>
[...]
<option value="34" selected="selected">34</option>
[...]
<option value="59">59</option>
</select></td></tr>
</code></pre>
<p>Check that your request.POST is correct.</p>
<p>As a sidenote, are you sure this widget gives good usability? Four mouse clicks and possible scrolling of the minutes combobox...</p>
| 0
|
2009-02-12T10:00:40Z
|
[
"python",
"django",
"forms",
"widget",
"field"
] |
Custom django widget - decompress() arg not populated
| 539,899
|
<p>As an exercise I am trying to create a custom django widget for a 24 hour clock. The widget will is a MultiWidget - a select box for each field.</p>
<p>I am trying to follow docs online (kinda sparse) and looking at the Pro Django book, but I can't seem to figure it out. Am I on the right track? I can save my data from the form, but when I prepopulate the form, the form doesn't have the previous values. </p>
<p>It seems the issue is that the decompress() methods 'value' argument is always empty, so I have nothing to interpret.</p>
<pre><code>from django.forms import widgets
import datetime
class MilitaryTimeWidget(widgets.MultiWidget):
"""
A widget that displays 24 hours time selection.
"""
def __init__(self, attrs=None):
hours = [ (i, "%02d" %(i)) for i in range(0, 24) ]
minutes = [ (i, "%02d" %(i)) for i in range(0, 60) ]
_widgets = (
widgets.Select(attrs=attrs, choices=hours),
widgets.Select(attrs=attrs, choices=minutes),
)
super(MilitaryTimeWidget, self).__init__(_widgets, attrs)
def decompress(self, value):
print "******** %s" %value
if value:
return [int(value.hour), int(value.minute)]
return [None, None]
def value_from_datadict(self, data, files, name):
hour = data.get("%s_0" %name, None)
minute = data.get("%s_1" %name, None)
if hour and minute:
hour = int(hour)
minute = int(minute)
return datetime.time(hour=hour, minute=minute)
return None
</code></pre>
<p>In my form, I am calling the widget like:</p>
<pre><code>arrival_time = forms.TimeField(label="Arrival Time", required=False, widget=MilitaryTimeWidget())
</code></pre>
| 3
|
2009-02-12T03:30:40Z
| 542,656
|
<p>Note <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py#L582" rel="nofollow">this line in the docstring for MultiWidget</a>:</p>
<blockquote>
<p>You'll probably want to use this class with MultiValueField.</p>
</blockquote>
<p>That's the root of your problem. You might be able to get the single-widget-only approach working (Marty says it's possible in <em>Pro Django</em>, but I've never tried it, and I think it's likely to be more work), but in that case your widget shouldn't be a subclass of MultiWidget.</p>
<p>What you need to do (if you want to follow the MultiWidget/MultiValueField path) is:</p>
<ul>
<li>remove your value_from_datadict method</li>
<li>define a subclass of <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L740" rel="nofollow">MultiValueField</a> with a definition of the compress() method which does the task you're currently doing in value_from_datadict() (transforming a list of numbers into a datetime.time object)</li>
<li>set your Widget as the default one for your custom form Field (using the widget class attribute)</li>
<li>either create a custom model Field which returns your custom form Field from its formfield() method, or use your custom form field manually as a field override in a ModelForm. </li>
</ul>
<p>Then everything will Just Work.</p>
| 3
|
2009-02-12T18:26:20Z
|
[
"python",
"django",
"forms",
"widget",
"field"
] |
How to Install Satchmo in Windows?
| 540,046
|
<p>I'm working on a Django project that's slated to be using Satchmo for its e-commerce aspects. I'd like to install it on my Windows Vista machine but some of the cPython modules it needs can't be compiled or easy_installed.</p>
<p>Has anyone been able to get Satchmo working on Windows, and if so, what additional steps does it take over the installation instructions?</p>
| 0
|
2009-02-12T04:40:04Z
| 544,322
|
<p>Which modules are you having trouble with?
Pycrypto binaries are here - <a href="http://www.voidspace.org.uk/python/modules.shtml#pycrypto" rel="nofollow">http://www.voidspace.org.uk/python/modules.shtml#pycrypto</a>
Python Imaging binaries are here - <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a></p>
<p>I believe everything else is pure python so it should be pretty simple to install the rest.</p>
| 3
|
2009-02-13T01:12:15Z
|
[
"python",
"windows",
"django",
"windows-vista",
"satchmo"
] |
Python 3.0 urllib.parse error "Type str doesn't support the buffer API"
| 540,342
|
<pre><code> File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
self.read_urlencoded()
File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
self.strict_parsing):
File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
</code></pre>
<p>Can anybody direct me on how to avoid this? I'm getting it through feeding data into the <code>cgi.Fieldstorage</code> and I can't seem to do it any other way.</p>
| 21
|
2009-02-12T07:24:05Z
| 542,080
|
<p>urllib is trying to do:</p>
<pre><code>b'a,b'.split(',')
</code></pre>
<p>Which doesn't work. byte strings and unicode strings mix even less smoothly in Py3k than they used toâââdeliberately, to make encoding problems go wrong sooner rather than later.</p>
<p>So the error is rather opaquely telling you âyou can't pass a byte string to urllib.parseâ. Presumably you are doing a POST request, where the form-encoded string is coming into cgi as a content body; the content body is still a byte string/stream so it now clashes with the new urllib.</p>
<p>So yeah, it's a bug in cgi.py, yet another victim of 2to3 conversion that hasn't been fixed properly for the new string model. It should be converting the incoming byte stream to characters before passing them to urllib.</p>
<p>Did I mention Python 3.0's libraries (especially web-related ones) still being rather shonky? :-)</p>
| 25
|
2009-02-12T16:14:50Z
|
[
"python",
"cgi",
"python-3.x",
"urllib"
] |
Python 3.0 urllib.parse error "Type str doesn't support the buffer API"
| 540,342
|
<pre><code> File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__
self.read_urlencoded()
File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded
self.strict_parsing):
File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
</code></pre>
<p>Can anybody direct me on how to avoid this? I'm getting it through feeding data into the <code>cgi.Fieldstorage</code> and I can't seem to do it any other way.</p>
| 21
|
2009-02-12T07:24:05Z
| 2,159,263
|
<p>From the python tutorial ( <a href="http://www.python.org/doc/3.0/tutorial/stdlib.html">http://www.python.org/doc/3.0/tutorial/stdlib.html</a> ) there is an example of using urlopen method. It raises the same error.</p>
<pre><code>for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
if 'EST' in line or 'EDT' in line: # look for Eastern Time
print(line)
</code></pre>
<p>You'll need to use the str function to convert the byte thingo to a string with the correct encoding. As follows:</p>
<pre><code>for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
lineStr = str( line, encoding='utf8' )
if 'EST' in lineStr or 'EDT' in lineStr: # look for Eastern Time
print(lineStr)
</code></pre>
| 14
|
2010-01-29T01:13:39Z
|
[
"python",
"cgi",
"python-3.x",
"urllib"
] |
C to Python via SWIG: can't get void** parameters to hold their value
| 540,427
|
<p>I have a C interface that looks like this (simplified):</p>
<pre><code>extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);
</code></pre>
<p>which is used as follows:</p>
<pre><code>void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p))
{
theAnswer = GetFieldValue(p);
Cleanup(p);
}
</code></pre>
<p>You'll note that Operation() allocates the buffer p, that GetFieldValue queries p, and that Cleanup frees p. I don't have any control over the C interface -- that code is widely used elsewhere.</p>
<p>I'd like to call this code from Python via <a href="http://www.swig.org/" rel="nofollow">SWIG</a>, but I was unable to find any good examples of how to pass a pointer to a pointer -- and retrieve its value.</p>
<p>I think the correct way to do this is by use of typemaps, so I defined an interface that would automatically dereference p for me on the C side:</p>
<pre><code>%typemap(in) void** {
$1 = (void**)&($input);
}
</code></pre>
<p>However, I was unable to get the following python code to work:</p>
<pre><code>import test
p = None
theAnswer = 0.0f
if test.Operation(p):
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
</code></pre>
<p>After calling test.Operation(), p always kept its initial value of None. </p>
<p>Any help with figuring out the correct way to do this in SWIG would be much appreciated. Otherwise, I'm likely to just write a C++ wrapper around the C code that stops Python from having to deal with the pointer. And then wrap <em>that</em> wrapper with SWIG. Somebody stop me!</p>
<p>Edit:</p>
<p>Thanks to <a href="http://stackoverflow.com/users/7161/jorenko">Jorenko</a>, I now have the following SWIG interface:</p>
<pre><code>% module Test
%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1, Cleanup);
$result = PyTuple_Pack(2, $result, obj);
}
%{
extern bool Operation(void ** ppData);
extern float GetFieldValue(void *p);
extern void Cleanup(void *p);
%}
%inline
%{
float gfv(void *p){ return GetFieldValue(p);}
%}
%typemap (in) void*
{
if (PyCObject_Check($input))
{
$1 = PyCObject_AsVoidPtr($input);
}
}
</code></pre>
<p>The python code that uses this SWIG interface is as follows:</p>
<pre><code>import test
success, p = test.Operation()
if success:
f = test.GetFieldValue(p) # This doesn't work
f = test.gvp(p) # This works!
test.Cleanup(p)
</code></pre>
<p>Oddly, in the python code, test.GetFieldValue(p) returns gibberish, but test.gfv(p) returns the correct value. I've inserting debugging code into the typemap for void*, and both have the same value of p! The call Any ideas about that?</p>
<p><strong>Update:</strong> I've decided to use ctypes. MUCH easier.</p>
| 7
|
2009-02-12T08:04:16Z
| 540,507
|
<p>Would you be willing to use ctypes? Here is sample code that should work (although it is untested):</p>
<pre><code>from ctypes import *
test = cdll("mydll")
test.Operation.restype = c_bool
test.Operation.argtypes = [POINTER(c_void_p)]
test.GetFieldValue.restype = c_float
test.GetFieldValue.argtypes = [c_void_p]
test.Cleanup.restype = None
test.Cleanup.argtypes = [c_void_p]
if __name__ == "__main__":
p = c_void_p()
if test.Operation(byref(p)):
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
</code></pre>
| 4
|
2009-02-12T08:39:09Z
|
[
"python",
"c",
"swig",
"wrapping"
] |
C to Python via SWIG: can't get void** parameters to hold their value
| 540,427
|
<p>I have a C interface that looks like this (simplified):</p>
<pre><code>extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);
</code></pre>
<p>which is used as follows:</p>
<pre><code>void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p))
{
theAnswer = GetFieldValue(p);
Cleanup(p);
}
</code></pre>
<p>You'll note that Operation() allocates the buffer p, that GetFieldValue queries p, and that Cleanup frees p. I don't have any control over the C interface -- that code is widely used elsewhere.</p>
<p>I'd like to call this code from Python via <a href="http://www.swig.org/" rel="nofollow">SWIG</a>, but I was unable to find any good examples of how to pass a pointer to a pointer -- and retrieve its value.</p>
<p>I think the correct way to do this is by use of typemaps, so I defined an interface that would automatically dereference p for me on the C side:</p>
<pre><code>%typemap(in) void** {
$1 = (void**)&($input);
}
</code></pre>
<p>However, I was unable to get the following python code to work:</p>
<pre><code>import test
p = None
theAnswer = 0.0f
if test.Operation(p):
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
</code></pre>
<p>After calling test.Operation(), p always kept its initial value of None. </p>
<p>Any help with figuring out the correct way to do this in SWIG would be much appreciated. Otherwise, I'm likely to just write a C++ wrapper around the C code that stops Python from having to deal with the pointer. And then wrap <em>that</em> wrapper with SWIG. Somebody stop me!</p>
<p>Edit:</p>
<p>Thanks to <a href="http://stackoverflow.com/users/7161/jorenko">Jorenko</a>, I now have the following SWIG interface:</p>
<pre><code>% module Test
%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1, Cleanup);
$result = PyTuple_Pack(2, $result, obj);
}
%{
extern bool Operation(void ** ppData);
extern float GetFieldValue(void *p);
extern void Cleanup(void *p);
%}
%inline
%{
float gfv(void *p){ return GetFieldValue(p);}
%}
%typemap (in) void*
{
if (PyCObject_Check($input))
{
$1 = PyCObject_AsVoidPtr($input);
}
}
</code></pre>
<p>The python code that uses this SWIG interface is as follows:</p>
<pre><code>import test
success, p = test.Operation()
if success:
f = test.GetFieldValue(p) # This doesn't work
f = test.gvp(p) # This works!
test.Cleanup(p)
</code></pre>
<p>Oddly, in the python code, test.GetFieldValue(p) returns gibberish, but test.gfv(p) returns the correct value. I've inserting debugging code into the typemap for void*, and both have the same value of p! The call Any ideas about that?</p>
<p><strong>Update:</strong> I've decided to use ctypes. MUCH easier.</p>
| 7
|
2009-02-12T08:04:16Z
| 541,566
|
<p>I agree with theller, you should use ctypes instead. It's always easier than thinking about typemaps.</p>
<p>But, if you're dead set on using swig, what you need to do is make a typemap for <code>void**</code> that RETURNS the newly allocated <code>void*</code>:</p>
<pre><code>%typemap (in,numinputs=0) void** (void *temp)
{
$1 = &temp;
}
%typemap (argout) void**
{
PyObject *obj = PyCObject_FromVoidPtr(*$1);
$result = PyTuple_Pack(2, $result, obj);
}
</code></pre>
<p>Then your python looks like:</p>
<pre><code>import test
success, p = test.Operation()
theAnswer = 0.0f
if success:
theAnswer = test.GetFieldValue(p)
test.Cleanup(p)
</code></pre>
<p>Edit:</p>
<p>I'd expect swig to handle a simple by-value <code>void*</code> arg gracefully on its own, but just in case, here's swig code to wrap the <code>void*</code> for GetFieldValue() and Cleanup():</p>
<pre><code>%typemap (in) void*
{
$1 = PyCObject_AsVoidPtr($input);
}
</code></pre>
| 7
|
2009-02-12T14:46:30Z
|
[
"python",
"c",
"swig",
"wrapping"
] |
Pydev and Pylons inside virtual environment, auto completion wonât work
| 540,538
|
<p>I have Pydev installed and running without problem with Python 2.6. I installed Pylons 0.9.7 RC 4 into virtual environment, then configured new interpreter to pint into virtual environment and this one is used for pylons project. My problem is that code auto completion does not work for a classes from base library (one that are installed with base python installation), and it works without any problem with classes from virtual environment.</p>
<p>TIA</p>
| 3
|
2009-02-12T08:53:12Z
| 565,309
|
<p>perhaps <a href="http://www.nabble.com/-pydev---Users--Multiple-Interpreters-td17679628.html" rel="nofollow">this</a> or <a href="http://groups.google.com/group/pylons-discuss/browse_thread/thread/916ab8ac6c2ae746?fwc=1&pli=1" rel="nofollow">this</a> would help</p>
<p><em>BTW: I guess that this is the correct behavior, this interpreter uses only the packages that are installed withing the virtualenv (this is the whole intent and purpose of the virtualenv isn't it?)</em></p>
| 4
|
2009-02-19T13:32:44Z
|
[
"python",
"pylons",
"pydev",
"virtualenv"
] |
Specify a sender when sending mail with Python (smtplib)
| 540,976
|
<p>I have a very simple piece of code (just for testing):</p>
<pre><code>import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
</code></pre>
<p>This works but the problem is that e-mail clients don't display a sender.
I want to be able to add a sender name to the e-mail. Suggestions?</p>
| 4
|
2009-02-12T11:52:40Z
| 541,003
|
<p><code>smtplib</code> doesn't automatically include a <code>From:</code> header, so you have to put one in yourself:</p>
<pre><code>message = 'From: me@example.com\nSubject: [PGS]: Results\n\nBlaBlaBla'
</code></pre>
<p>(In fact, <code>smtplib</code> doesn't include <em>any</em> headers automatically, but just sends the text that you give it as a raw message)</p>
| 6
|
2009-02-12T12:08:12Z
|
[
"python",
"email"
] |
Specify a sender when sending mail with Python (smtplib)
| 540,976
|
<p>I have a very simple piece of code (just for testing):</p>
<pre><code>import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
</code></pre>
<p>This works but the problem is that e-mail clients don't display a sender.
I want to be able to add a sender name to the e-mail. Suggestions?</p>
| 4
|
2009-02-12T11:52:40Z
| 541,020
|
<p>You can utilize the <a href="http://docs.python.org/library/email.message.html#email.message.Message">email.message.Message</a> class, and use it to generate mime headers, including <code>from:</code>, <code>to:</code> and <code>subject</code>. Send the <code>as_string()</code> result via SMTP.</p>
<pre><code>>>> from email import message
>>> m1=message.Message()
>>> m1.add_header('from','me@no.where')
>>> m1.add_header('to','myself@some.where')
>>> m1.add_header('subject','test')
>>> m1.set_payload('test\n')
>>> m1.as_string()
'from: me@no.where\nto: myself@some.where\nsubject: test\n\ntest\n'
>>>
</code></pre>
| 11
|
2009-02-12T12:16:10Z
|
[
"python",
"email"
] |
Specify a sender when sending mail with Python (smtplib)
| 540,976
|
<p>I have a very simple piece of code (just for testing):</p>
<pre><code>import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
</code></pre>
<p>This works but the problem is that e-mail clients don't display a sender.
I want to be able to add a sender name to the e-mail. Suggestions?</p>
| 4
|
2009-02-12T11:52:40Z
| 541,030
|
<p>The "sender" you're specifying in this case is the envelope sender that is passed onto the SMTP server.</p>
<p>What your MUA (Mail User Agent - i.e. outlook/Thunderbird etc.) shows you is the "From:" header.</p>
<p>Normally, if I'm using smtplib, I'd compile the headers separately:</p>
<pre><code>headers = "From: %s\nTo: %s\n\n" % (email_from, email_to)
</code></pre>
<p>The format of the From header is by convention normally <code>"Name" <user@domain></code></p>
<p>You should be including a "Message-Id" header and a "Reply-To" header as well in all communications. Especially since spam filters may pick up on the lack of these as a great probability that the mail is spam.</p>
<p>If you've got your mail body in the variable body, just compile the overall message with:</p>
<pre><code>message = headers + body
</code></pre>
<p>Note the double newline at the end of the headers. It's also worth noting that SMTP servers should separate headers with newlines only (i.e. LF - linfeed). However, I have seen a Windows SMTP server or two that uses \r\n (i.e. CRLF). If you're on Windows, YMMV.</p>
| 7
|
2009-02-12T12:22:54Z
|
[
"python",
"email"
] |
Specify a sender when sending mail with Python (smtplib)
| 540,976
|
<p>I have a very simple piece of code (just for testing):</p>
<pre><code>import smtplib
import time
server = 'smtp.myprovider.com'
recipients = ['johndoe@somedomain.com']
sender = 'me@mydomain.com'
message = 'Subject: [PGS]: Results\n\nBlaBlaBla'
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
</code></pre>
<p>This works but the problem is that e-mail clients don't display a sender.
I want to be able to add a sender name to the e-mail. Suggestions?</p>
| 4
|
2009-02-12T11:52:40Z
| 26,717,984
|
<p><a href="http://stackoverflow.com/a/10553563/486556">See</a> this answer, it's working for me.</p>
<p>example code:</p>
<pre><code>#send html email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
msg = MIMEMultipart('alternative')
msg['From'] = formataddr((str(Header('MyWebsite', 'utf-8')), 'from@mywebsite.com'))
msg['To'] = 'to@email.com'
html = "email contents"
# Record the MIME types of text/html.
msg.attach(MIMEText(html, 'html'))
# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail('from@mywebsite.com', 'to@email.com', msg.as_string())
s.quit()
</code></pre>
| 5
|
2014-11-03T15:58:16Z
|
[
"python",
"email"
] |
Python Imaging Library and JPEGs on MacOsX
| 540,991
|
<p>I've gotten a hold of <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library (PIL)</a> and installed the PNG support stuff just fine. I am however having issues with the<a href="http://www.ijg.org/" rel="nofollow">JPEG Library</a>.</p>
<p>The default setting for it is nothing but they suggest "/home/libraries/jpeg-6b". On the Mac that directory doesn't exist, the library is however installed fine, here's the output of the install.</p>
<pre><code>/usr/bin/install -c cjpeg /usr/local/bin/cjpeg
/usr/bin/install -c djpeg /usr/local/bin/djpeg
/usr/bin/install -c jpegtran /usr/local/bin/jpegtran
/usr/bin/install -c rdjpgcom /usr/local/bin/rdjpgcom
/usr/bin/install -c wrjpgcom /usr/local/bin/wrjpgcom
/usr/bin/install -c -m 644 ./cjpeg.1 /usr/local/man/man1/cjpeg.1
/usr/bin/install -c -m 644 ./djpeg.1 /usr/local/man/man1/djpeg.1
/usr/bin/install -c -m 644 ./jpegtran.1 /usr/local/man/man1/jpegtran.1
/usr/bin/install -c -m 644 ./rdjpgcom.1 /usr/local/man/man1/rdjpgcom.1
/usr/bin/install -c -m 644 ./wrjpgcom.1 /usr/local/man/man1/wrjpgcom.1
</code></pre>
<p>I tried pointing PIL to /usr/local/bin/cjpeg, cjpeg and so on but it never recognised it. Does anybody know what I'm doing wrong?</p>
| 2
|
2009-02-12T12:04:12Z
| 541,067
|
<p>For me, the only way to have working Python + PIL on OS X was to install both from <a href="http://www.macports.org/" rel="nofollow">ports</a>. I've never managed to get fully functional PIL under either system Python or installed manually from python.org. Maybe you could try this approach?</p>
| 5
|
2009-02-12T12:38:46Z
|
[
"python",
"osx",
"jpeg",
"python-imaging-library"
] |
Finding top-level xml comments using Python's ElementTree
| 541,100
|
<p>I'm parsing an xml file using Python's ElementTree, like that: </p>
<pre><code>et = ElementTree(file=file("test.xml"))
</code></pre>
<p>test.xml starts with a few lines of xml comments. </p>
<p>Is there a way to get those comments from et?</p>
| 3
|
2009-02-12T12:50:15Z
| 541,117
|
<p>For ElementTree 1.2.X there is an article on <a href="http://effbot.org/zone/element-pi.htm" rel="nofollow">Reading processing instructions and comments with ElementTree
</a> (<a href="http://effbot.org/zone/element-pi.htm" rel="nofollow">http://effbot.org/zone/element-pi.htm</a>).</p>
<p><hr /></p>
<p><em>EDIT:</em></p>
<p>The alternative would be using <strong>lxml.etree</strong> which implements the ElementTree API. A quote from <a href="http://codespeak.net/lxml/compatibility.html" rel="nofollow">ElementTree compatibility of lxml.etree
</a>:</p>
<blockquote>
<p><strong>ElementTree ignores comments</strong> and
processing instructions when parsing
XML, while <strong>etree will read them in</strong> and
treat them as Comment or
ProcessingInstruction elements
respectively.</p>
</blockquote>
| 4
|
2009-02-12T12:55:05Z
|
[
"python",
"xml",
"elementtree"
] |
How to lookup custom ip address field stored as integer in Django-admin?
| 541,115
|
<p>In my Django model I've created custom MyIPAddressField which is stored as integer in mysql backend. To do that I've implemented to_python, get_db_prep_value, get_iternal_type (returns PositiveIntegerField) and formfield methods (uses stock IPAddressField as form_class).</p>
<p>The only problem is field lookup in cases like builtin search in ModelAdmin. So, the question is how to implement get_db_prep_lookup to perform string-based lookup types like 'contains', 'regex', 'startswith', 'endswith'?</p>
<p>Mysql has special function inet_ntoa() but I don't know how to instruct ORM to use it in admin search queries. For example: SELECT inet_ntoa(ip_address) as ip FROM table WHERE ip LIKE '%search_term%'. Why custom fields perform type casting on python side but not on database side?</p>
<p>EDIT1: probably there is another way to solve search problem - don't transform integer column to string, but instead split search argument into subnet/mask and perform some binary math to compare them against integer IP value.</p>
<p>EDIT2: this is my code so far:</p>
<p>models.py:</p>
<pre><code>class MyIPField(models.Field):
empty_strings_allowed = False
__metaclass__ = models.SubfieldBase
def get_db_prep_value(self, value):
if value is None: return None
return unpack('!L', inet_aton(value))[0]
def get_internal_type(self):
return "PositiveIntegerField"
def to_python(self, value):
if type(value).__name__ in ('NoneType', 'unicode'): return value
return inet_ntoa(pack('!L', value))
def formfield(self, **kwargs):
defaults = {'form_class': IPAddressField}
defaults.update(kwargs)
return super(MyIPField, self).formfield(**defaults)
class MyManager(models.Manager):
def get_query_set(self):
return super(MyManager, self).get_query_set().extra(select={'fakeip': "inet_ntoa(ip)"})
class Address(models.Model):
# ... other fields are skipped (Note: there was several foreign keys)
ip = MyIPField(u"IP address", unique=True)
objects = AddressManager()
def __unicode__(self):
return self.ip
</code></pre>
<p>admin.py:</p>
<pre><code>class AddressAdmin(admin.ModelAdmin):
list_display = ('address',) # ... some fields are skipped from this example
list_display_links = ('address',)
search_fields = ('fakeip', )
admin.site.register(Address, AddressAdmin)
</code></pre>
<p>But when I use admin changelist search box, I get error "Can not resolve keyword 'fakeip' into field. Choices are: ip, id". Is it possible to fool Django and make it think that fakeip is a real field?</p>
<p>Using standard IPAddressField (string based) is not appropriate for my needs, as well as switching to Postgres where it stored in proper format.</p>
<p>Also I've looked to Django admin internals (options.py and views/main.py), and I see no easy way to customize ChangeList class or search mechanics without massive copy/pasting. I thought that Django admin is more powerful than it is.</p>
| 3
|
2009-02-12T12:54:42Z
| 558,461
|
<p>You could instruct the ORM to add an extra field to your SQL queries, like so:</p>
<pre><code>IPAddressModel.objects.extra(select={'ip': "inet_ntoa(ip_address)"})
</code></pre>
<p>This adds <code>SELECT inet_ntoa(ip_address) as ip</code> to the query and a field <code>ip</code> to your objects. You can use the new synthesized field in your WHERE clause.</p>
<p>Are you sure you don't really want something like <code>WHERE (ip_address & 0xffff0000) = inet_aton('192.168.0.0')</code>? Or do you <em>really</em> want to find all ip addresses in your log that contain the number <code>119</code> somewhere?</p>
<p>If <code>suffix</code> is the /24 from CIDR notation:</p>
<pre><code>mask = 0xffffffff ^ 0xffffffff >> suffix
</code></pre>
<p>Add to the WHERE clause:</p>
<pre><code>(ip_address & mask) = (inet_aton(prefix) & mask)
</code></pre>
| 2
|
2009-02-17T19:55:13Z
|
[
"python",
"mysql",
"django"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 541,397
|
<p>The expat python bindings included in the normal Python distribution is constructing stack frames programtically. Be warned though, it relies on undocumented and private APIs.</p>
<p><a href="http://svn.python.org/view/python/trunk/Modules/pyexpat.c?rev=64048&view=auto">http://svn.python.org/view/python/trunk/Modules/pyexpat.c?rev=64048&view=auto</a></p>
| 9
|
2009-02-12T14:13:19Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 541,529
|
<p>You could grab the existing stack frame by throwing an exception and stepping back one frame along in the traceback. The problem is there is no way provided to resume execution in the middle (frame.f_lasti) of the code block.</p>
<p>âResumable exceptionsâ are a really interesting language idea, although it's tricky to think of a reasonable way they could interact with Python's existing âtry/finallyâ and âwithâ blocks.</p>
<p>For the moment, the normal way of doing this is simply to use threads to run your workflow in a separate context to its controller. (Or coroutines/greenlets if you don't mind compiling them in).</p>
| 2
|
2009-02-12T14:37:18Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 542,285
|
<p>What you generally want are continuations, which I see is already a tag on this question.</p>
<p>If you have the ability to work with all of the code in the system, you may want to try
doing it this way rather than dealing with the interpreter stack internals. I'm not sure how easily this will be persisted.</p>
<p><a href="http://www.ps.uni-sb.de/~duchier/python/continuations.html" rel="nofollow">http://www.ps.uni-sb.de/~duchier/python/continuations.html</a></p>
<p>In practice, I would structure your workflow engine so that your script submits action objects to a manager. The manager could pickle the set of actions at any point and allow
them to be loaded and begin execution again (by resuming the submission of actions).</p>
<p>In other words: make your own, application-level, stack.</p>
| 5
|
2009-02-12T16:59:17Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 1,523,359
|
<p>I have the same type of problem to solve. I wonder what the original poster decided to do.</p>
<p>stackless claims it can pickle tasklets as long as there's no associated 'encumbered' C stack (encumbered is my choice of phrasing).</p>
<p>I'll probably use eventlet and figure out some way of pickling 'state', I really don't want to write an explicit state machine though.. </p>
| 1
|
2009-10-06T02:48:16Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 7,389,508
|
<p>With standard CPython this is complicated by the mixture of C and Python data in the stack. Rebuilding the call stack would require the C stack to be reconstructed at the same time. This really puts it in the too hard basket as it could potentially tightly couple the implementation to specific versions of CPython.</p>
<p>Stackless Python allows tasklets to be pickled, which gives most of the capability required out of the box.</p>
| 2
|
2011-09-12T14:31:32Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 17,405,053
|
<p>How about using <a href="http://pythonhosted.org/joblib/" rel="nofollow">joblib</a>?</p>
<p>I'm not quite sure this is what you want but it seems to fit the idea of having a workflow of which stages can be persisted. Joblib's use case seems to be to avoid recomputation, I'm not sure if this is what you are trying to do here or something more complicated?</p>
| 1
|
2013-07-01T12:58:26Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
| 541,329
|
<p>Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario:</p>
<ol>
<li><p>You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine.</p></li>
<li><p>A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort.</p></li>
<li><p>You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine.</p></li>
<li><p>The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later.</p></li>
<li><p>In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script.</p></li>
<li><p>The event dispatching engine fires the event that the wait condition picks up.</p></li>
<li><p>The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called.</p></li>
</ol>
<p><strong>The Question</strong></p>
<p>Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code?</p>
<p><strong>Edit:</strong> To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one.</p>
<p><strong>Update:</strong> From some initial investigation, one can get the execution context with <code>PyThreadState_Get()</code>. This returns the thread state in a <code>PyThreadState</code> (defined in <code>pystate.h</code>), which has a reference to the stack frame in <code>frame</code>. A stack frame is held in a struct typedef'd to <code>PyFrameObject</code>, which is defined in <code>frameobject.h</code>. <code>PyFrameObject</code> has a field <code>f_lasti</code> (props to <a href="http://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529">bobince</a>) which has a program counter expressed as an offset from the beginning of the code block.</p>
<p>This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter.</p>
<p>The three remaining problems are: </p>
<ul>
<li><p>Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished.</p></li>
<li><p>Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading <code>__locals__</code> (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here.</p></li>
<li><p>Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor
In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. </p></li>
</ul>
<p><strong>Update 2:</strong> <code>PyCodeObject</code> (<code>code.h</code>) has a list of addr (<code>f_lasti</code>)-> line number mappings in <code>PyCodeObject.co_lnotab</code> (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising.</p>
<p><strong>Update 3:</strong> I think the answer to this might be <a href="http://www.stackless.com">Stackless Python.</a> You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.</p>
| 20
|
2009-02-12T13:53:02Z
| 21,350,914
|
<p>Stackless python is probably the best⦠if you don't mind totally going over to a different python distribution. <code>stackless</code> can serialize <strong>everything</strong> in python, plus their tasklets. If you want to stay in the standard python distribution, then I'd use <a href="https://github.com/uqfoundation/dill" rel="nofollow">dill</a>, which can serialize <strong>almost</strong> anything in python.</p>
<pre><code>>>> import dill
>>>
>>> def foo(a):
... def bar(x):
... return a*x
... return bar
...
>>> class baz(object):
... def __call__(self, a,x):
... return foo(a)(x)
...
>>> b = baz()
>>> b(3,2)
6
>>> c = baz.__call__
>>> c(b,3,2)
6
>>> g = dill.loads(dill.dumps(globals()))
>>> g
{'dill': <module 'dill' from '/Library/Frameworks/Python.framework/Versions/7.2/lib/python2.7/site-packages/dill-0.2a.dev-py2.7.egg/dill/__init__.pyc'>, 'c': <unbound method baz.__call__>, 'b': <__main__.baz object at 0x4d61970>, 'g': {...}, '__builtins__': <module '__builtin__' (built-in)>, 'baz': <class '__main__.baz'>, '_version': '2', '__package__': None, '__name__': '__main__', 'foo': <function foo at 0x4d39d30>, '__doc__': None}
</code></pre>
<p>Dill registers it's types into the <code>pickle</code> registry, so if you have some black box code that uses <code>pickle</code> and you can't really edit it, then just importing dill can magically make it work without monkeypatching the 3rd party code.</p>
<p>Here's <code>dill</code> pickling the whole interpreter session... </p>
<pre><code>>>> # continuing from above
>>> dill.dump_session('foobar.pkl')
>>>
>>> ^D
dude@sakurai>$ python
Python 2.7.5 (default, Sep 30 2013, 20:15:49)
[GCC 4.2.1 (Apple Inc. build 5566)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('foobar.pkl')
>>> c(b,3,2)
6
</code></pre>
<p><code>dill</code> also has <a href="https://github.com/uqfoundation/dill/blob/master/dill/detect.py" rel="nofollow">some good tools</a> for helping you understand what is causing your pickling to fail when your code fails.</p>
<p>You also asked for where it's used to save interpreter state?</p>
<p><a href="https://github.com/ipython/ipython" rel="nofollow">IPython</a> can use <code>dill</code> to save the interpreter session to a file. <a href="https://nbtest.herokuapp.com/github/ipython/ipython/blob/master/examples/parallel/Using%20Dill.ipynb" rel="nofollow">https://nbtest.herokuapp.com/github/ipython/ipython/blob/master/examples/parallel/Using%20Dill.ipynb</a></p>
<p><a href="https://github.com/uqfoundation/klepto" rel="nofollow">klepto</a> uses <code>dill</code> to support in-memory, to-disk, or to-database caching that avoids recomputation. <a href="https://github.com/uqfoundation/klepto/blob/master/tests/test_cache_info.py" rel="nofollow">https://github.com/uqfoundation/klepto/blob/master/tests/test_cache_info.py</a></p>
<p><a href="https://github.com/uqfoundation/mystic" rel="nofollow">mystic</a> uses <code>dill</code> to save the checkpoints for large optimization jobs by saving the state of the optimizer as it's in progress. <a href="https://github.com/uqfoundation/mystic/blob/master/tests/test_solver_state.py" rel="nofollow">https://github.com/uqfoundation/mystic/blob/master/tests/test_solver_state.py</a></p>
<p>There are a couple other packages that use <code>dill</code> to save state of objects or sessions.</p>
| 2
|
2014-01-25T13:04:32Z
|
[
"python",
"serialization",
"stack",
"continuations",
"python-stackless"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 541,394
|
<p>Yes. Use <a href="https://docs.python.org/2/library/os.path.html#os.path.splitext"><code>os.path.splitext</code></a>:</p>
<pre><code>>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
</code></pre>
| 970
|
2009-02-12T14:12:46Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 541,408
|
<pre><code>import os.path
extension = os.path.splitext(filename)[1]
</code></pre>
| 234
|
2009-02-12T14:15:07Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 7,202,805
|
<pre><code>import os.path
extension = os.path.splitext(filename)[1][1:]
</code></pre>
<p>To get only text extension </p>
| 58
|
2011-08-26T09:37:47Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 7,719,562
|
<p>Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the <code>strip()</code> method to the end. For example: </p>
<pre><code>import os.path
extension = os.path.splitext(filename)[1][1:].strip()
</code></pre>
| 7
|
2011-10-10T22:48:43Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 10,078,116
|
<p>One option may be splitting from dot:</p>
<pre><code>>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'
</code></pre>
<p>No error when file doesn't have an extension:</p>
<pre><code>>>> "filename".split(".")[-1]
'filename'
</code></pre>
<p>But you must be careful:</p>
<pre><code>>>> "png".split(".")[-1]
'png' # But file doesn't have an extension
</code></pre>
| 38
|
2012-04-09T18:48:16Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 14,066,130
|
<p>worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.</p>
<pre><code>os.path.splitext(filename)[1][1:].strip().lower()
</code></pre>
| 21
|
2012-12-28T07:25:49Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 14,698,139
|
<p>With splitext there are problems with files with double extension (e.g. <code>file.tar.gz</code>, <code>file.tar.bz2</code>, etc..)</p>
<pre><code>>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension
'.gz'
</code></pre>
<p>but should be: <code>.tar.gz</code></p>
<p>The possible solutions are <a href="http://stackoverflow.com/questions/6525334/getting-file-extension-using-pattern-matching-in-python">here</a></p>
| 5
|
2013-02-05T00:19:54Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 20,898,777
|
<p>Another solution with right split:</p>
<pre><code># to get extension only
s = 'test.ext'
if '.' in s: ext = s.rsplit('.', 1)[1]
# or, to get file name and extension
def split_filepath(s):
"""
get filename and extension from filepath
filepath -> (filename, extension)
"""
if not '.' in s: return (s, '')
r = s.rsplit('.', 1)
return (r[0], r[1])
</code></pre>
| 2
|
2014-01-03T07:32:02Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 21,851,612
|
<pre><code>filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
</code></pre>
| 6
|
2014-02-18T10:55:57Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 22,291,843
|
<p>If you know the exact file extension for example file.txt
then you can use</p>
<blockquote>
<blockquote>
<blockquote>
<p>print fileName[0:-4]</p>
</blockquote>
</blockquote>
</blockquote>
| -7
|
2014-03-10T03:57:06Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 25,454,134
|
<pre><code>name_only=file_name[:filename.index(".")
</code></pre>
<p>That will give you the file name up to the first ".", which would be the most common.</p>
| -4
|
2014-08-22T19:19:24Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 29,396,553
|
<pre class="lang-py prettyprint-override"><code># try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs
import os.path
class LinkChecker:
@staticmethod
def get_link_extension(link: str)->str:
if link is None or link == "":
return ""
else:
paths = os.path.splitext(link)
ext = paths[1]
new_link = paths[0]
if ext != "":
return LinkChecker.get_link_extension(new_link) + ext
else:
return ""
</code></pre>
| -1
|
2015-04-01T16:56:27Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 33,575,151
|
<pre><code>def NewFileName(fichier):
cpt = 0
fic , *ext = fichier.split('.')
ext = '.'.join(ext)
while os.path.isfile(fichier):
cpt += 1
fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
return fichier
</code></pre>
| 0
|
2015-11-06T20:24:11Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 34,376,810
|
<p>Surprised this wasn't mentioned yet:</p>
<pre><code>import os
fn = '/some/path/a.tar.gz'
basename = os.path.basename(fn) # os independent
Out[] a.tar.gz
base = basename.split('.')[0]
Out[] a
ext = '.'.join(basename.split('.')[1:]) # <-- main part
# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz
</code></pre>
<p>Benefits:</p>
<ul>
<li>Works as expected for anything I can think of</li>
<li>No modules</li>
<li>No regex</li>
<li>Cross-platform</li>
<li>Easily extendible (e.g. no leading dots for extension, only last part of extension)</li>
</ul>
<p>As function:</p>
<pre><code>def get_extension(filename):
basename = os.path.basename(filename) # os independent
ext = '.'.join(basename.split('.')[1:])
return '.' + ext if ext else None
</code></pre>
| 1
|
2015-12-20T00:24:08Z
|
[
"python",
"filenames",
"file-extension"
] |
Extracting extension from filename in Python
| 541,390
|
<p>Is there a function to extract the extension from a filename?</p>
| 599
|
2009-02-12T14:11:50Z
| 35,188,296
|
<p>I'm surprised no one has mentioned <a href="https://docs.python.org/3/library/pathlib.html"><code>pathlib</code></a> yet, <code>pathlib</code> IS awesome!</p>
<p><strong>NOTE:</strong> You require to have Python 3.4 at least though!</p>
<pre><code>import pathlib
print(pathlib.Path('yourPathGoesHere').suffix)
</code></pre>
<p>And if you want to get all the suffixes (for instance if you have a <code>.tar.gz</code>), <code>.suffixes</code> will return a list of them! Neat!</p>
| 13
|
2016-02-03T21:41:25Z
|
[
"python",
"filenames",
"file-extension"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 541,948
|
<p>Why do you want to create new scopes in python anyway?</p>
<p>The normal reason for doing it in other languages is variable scoping, but that doesn't happen in python.</p>
<pre><code>if True:
a = 10
print a
</code></pre>
| 4
|
2009-02-12T15:57:19Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 541,958
|
<p>variables in list comprehension (Python 3+) and generators are local:</p>
<pre><code>>>> i = 0
>>> [i+1 for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> i
0
</code></pre>
<p>but why exactly do you need this?</p>
| 0
|
2009-02-12T15:57:57Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 541,984
|
<p>I would see this as a clear sign that it's time to create a new function and refactor the code. I can see no reason to create a new scope like that. Any reason in mind?</p>
| 1
|
2009-02-12T16:01:19Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 541,996
|
<pre><code>def a():
def b():
pass
b()
</code></pre>
<p>If I just want some extra indentation or am debugging, I'll use <code>if True:</code></p>
| 0
|
2009-02-12T16:03:19Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 542,041
|
<p>In Python, scoping is of three types : global, local and class. You can create specialized 'scope' dictionaries to pass to exec / eval(). In addition you can use nested scopes
(defining a function within another). I found these to be sufficient in all my code.</p>
<p>As Douglas Leeder said already, the main reason to use it in other languages is variable scoping and that doesn't really happen in Python. In addition, Python is the most readable language I have ever used. It would go against the grain of readability to do something like if-true tricks (Which you say you want to avoid). In that case, I think the best bet is to refactor your code into multiple functions, or use a single scope. I think that the available scopes in Python are sufficient to cover every eventuality, so local scoping shouldn't really be necessary.</p>
<p>I hope this helps.</p>
| 5
|
2009-02-12T16:10:01Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 542,048
|
<p>If you just want to create temp variables and let them be garbage collected right after using them, you can use</p>
<pre><code>del varname
</code></pre>
<p>when you don't want them anymore. </p>
<p>If its just for aesthetics, you could use comments or extra newlines, no extra indentation, though.</p>
| 1
|
2009-02-12T16:11:08Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 542,114
|
<blockquote>
<p>A <em>scope</em> is a textual region of a
Python program where a namespace is
directly accessible. âDirectly
accessibleâ here means that an
unqualified reference to a name
attempts to find the name in the
namespace...</p>
</blockquote>
<p>Please, read <a href="http://docs.python.org/tutorial/classes.html#python-scopes-and-name-spaces" rel="nofollow">the documentation</a> and clarify your question.</p>
<p>btw, you don't need <code>if(TRUE){}</code> in C, a simple <code>{}</code> is sufficient. </p>
| 1
|
2009-02-12T16:21:43Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 542,120
|
<p>Python has exactly two scopes, local and global. Variables that are used in a function are in local scope no matter what indentation level they were created at. Calling a nested function will have the effect that you're looking for.</p>
<pre><code>def foo():
a = 1
def bar():
b = 2
print a, b #will print "1 2"
bar()
</code></pre>
<p>Still like everyone else, I have to ask you why you want to create a limited scope inside a function.</p>
| 0
|
2009-02-12T16:23:30Z
|
[
"python",
"scope"
] |
How can one create new scopes in python
| 541,926
|
<p>In many languages (and places) there is a nice practice of creating local scopes by creating a block like <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c">this</a>.</p>
<pre><code>void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
</code></pre>
<p>How can I implement this in python without getting the unexpected indent error and without using some sort of <a href="http://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c"><em>if True:</em></a> tricks</p>
| 6
|
2009-02-12T15:53:59Z
| 37,403,179
|
<p>Depending on your case, you might want <a href="https://docs.python.org/2/reference/compound_stmts.html#the-with-statement" rel="nofollow"><code>with</code> statement</a>:</p>
<pre><code>with Cat() as cat, Cake() as cake:
cat.eat(cake)
</code></pre>
<p>is equivalent to</p>
<pre><code># scope begin
cat = Cat()
cake = Cake()
cat.eat(cake)
# scope end
</code></pre>
| 1
|
2016-05-24T01:52:53Z
|
[
"python",
"scope"
] |
How to do variable assignment inside a while(expression) loop in Python?
| 542,212
|
<p>I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.</p>
<p>Here is how I'm doing it in PHP:</p>
<pre><code>while((name = raw_input("Name: ")) != ''):
names.append(name)
</code></pre>
<p>What I'm trying to do is identical to this in functionality: </p>
<pre><code>names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
</code></pre>
<p>Is there any way to do this in Python?</p>
| 12
|
2009-02-12T16:44:14Z
| 542,224
|
<p>No, sorry. It's a FAQ, explained well here:</p>
<p>In <a href="http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow" title="http://docs.python.org/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression">Pydocs</a>, and <a href="http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm" rel="nofollow" title="http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm">Fredrik Lundh's blog</a>.</p>
<blockquote>
<p>The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages.</p>
<p>Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.</p>
<p>An interesting phenomenon is that most experienced Python programmers recognize the <code>while True</code> idiom and donât seem to be missing the assignment in expression construct much; itâs only newcomers who express a strong desire to add this to the language.</p>
<p>Thereâs an alternative way of spelling this that seems attractive:</p>
<pre><code>line = f.readline() while line:
... # do something with line...
line = f.readline()
</code></pre>
</blockquote>
| 8
|
2009-02-12T16:48:34Z
|
[
"python",
"syntax",
"while-loop",
"expression"
] |
How to do variable assignment inside a while(expression) loop in Python?
| 542,212
|
<p>I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.</p>
<p>Here is how I'm doing it in PHP:</p>
<pre><code>while((name = raw_input("Name: ")) != ''):
names.append(name)
</code></pre>
<p>What I'm trying to do is identical to this in functionality: </p>
<pre><code>names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
</code></pre>
<p>Is there any way to do this in Python?</p>
| 12
|
2009-02-12T16:44:14Z
| 542,227
|
<p>You can wrap <code>raw_input()</code> to turn it into a generator:</p>
<pre><code>def wrapper(s):
while True:
result = raw_input(s)
if result = '': break
yield result
names = wrapper('Name:')
</code></pre>
<p>which means we're back to square one but with more complex code. So if you need to wrap an existing method, you need to use <a href="http://stackoverflow.com/users/17160/nosklo">nosklo</a>'s approach.</p>
| 12
|
2009-02-12T16:49:06Z
|
[
"python",
"syntax",
"while-loop",
"expression"
] |
How to do variable assignment inside a while(expression) loop in Python?
| 542,212
|
<p>I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.</p>
<p>Here is how I'm doing it in PHP:</p>
<pre><code>while((name = raw_input("Name: ")) != ''):
names.append(name)
</code></pre>
<p>What I'm trying to do is identical to this in functionality: </p>
<pre><code>names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
</code></pre>
<p>Is there any way to do this in Python?</p>
| 12
|
2009-02-12T16:44:14Z
| 544,564
|
<pre><code>from functools import partial
for name in iter(partial(raw_input, 'Name:'), ''):
do_something_with(name)
</code></pre>
<p>or if you want a list:</p>
<pre><code>>>> names = list(iter(partial(raw_input, 'Name: '), ''))
Name: nosklo
Name: Andreas
Name: Aaron
Name: Phil
Name:
>>> names
['nosklo', 'Andreas', 'Aaron', 'Phil']
</code></pre>
| 14
|
2009-02-13T02:58:59Z
|
[
"python",
"syntax",
"while-loop",
"expression"
] |
How to do variable assignment inside a while(expression) loop in Python?
| 542,212
|
<p>I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.</p>
<p>Here is how I'm doing it in PHP:</p>
<pre><code>while((name = raw_input("Name: ")) != ''):
names.append(name)
</code></pre>
<p>What I'm trying to do is identical to this in functionality: </p>
<pre><code>names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
</code></pre>
<p>Is there any way to do this in Python?</p>
| 12
|
2009-02-12T16:44:14Z
| 16,575,991
|
<p>I'm only 7 years late, but there's another solution. It's not the best solution I can think of, but it highlights an interesting use of the StopIteration exception. You can do a similar loop for chunk reading files/sockets and handle Timeouts and whatnot nicely.</p>
<pre><code>names=[]
try:
while True:
f = raw_input()
if not f:
raise StopIteration
else:
names.append(f)
except StopIteration:
pass
print names
</code></pre>
| 0
|
2013-05-15T22:23:29Z
|
[
"python",
"syntax",
"while-loop",
"expression"
] |
How to do variable assignment inside a while(expression) loop in Python?
| 542,212
|
<p>I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.</p>
<p>Here is how I'm doing it in PHP:</p>
<pre><code>while((name = raw_input("Name: ")) != ''):
names.append(name)
</code></pre>
<p>What I'm trying to do is identical to this in functionality: </p>
<pre><code>names = []
while(True):
name = raw_input("Name: ")
if (name == ''):
break
names.append(name)
</code></pre>
<p>Is there any way to do this in Python?</p>
| 12
|
2009-02-12T16:44:14Z
| 29,604,498
|
<pre><code>names = []
for name in iter(lambda: raw_input("Name: "), ''):
names.append(name)
</code></pre>
| 1
|
2015-04-13T11:45:03Z
|
[
"python",
"syntax",
"while-loop",
"expression"
] |
Are there any good build frameworks written in Python?
| 542,289
|
<p>I switched from NAnt to using Python to write build automation scripts. I am curious if whether any build frameworks worth using that are similar to Make, Ant, and NAnt, but, instead, are Python-based. For example, Ruby has Rake. What about Python?</p>
| 14
|
2009-02-12T16:59:28Z
| 542,309
|
<p>Try <a href="http://www.scons.org/" rel="nofollow">SCons</a> </p>
<p>Or are you looking for something just to build python projects?</p>
| 20
|
2009-02-12T17:01:59Z
|
[
"python",
"build-process",
"build-automation"
] |
Are there any good build frameworks written in Python?
| 542,289
|
<p>I switched from NAnt to using Python to write build automation scripts. I am curious if whether any build frameworks worth using that are similar to Make, Ant, and NAnt, but, instead, are Python-based. For example, Ruby has Rake. What about Python?</p>
| 14
|
2009-02-12T16:59:28Z
| 542,394
|
<p>The following look good, but I haven't used them (yet):</p>
<ul>
<li><a href="http://www.blueskyonmars.com/projects/paver/">Paver</a></li>
<li><a href="http://code.google.com/p/waf/">waf</a></li>
<li><a href="http://python-doit.sourceforge.net/">doIt</a></li>
</ul>
<p>Paver looks especially promising.</p>
| 5
|
2009-02-12T17:19:27Z
|
[
"python",
"build-process",
"build-automation"
] |
Are there any good build frameworks written in Python?
| 542,289
|
<p>I switched from NAnt to using Python to write build automation scripts. I am curious if whether any build frameworks worth using that are similar to Make, Ant, and NAnt, but, instead, are Python-based. For example, Ruby has Rake. What about Python?</p>
| 14
|
2009-02-12T16:59:28Z
| 545,191
|
<p>There is also <a href="http://www.nongnu.org/fab/" rel="nofollow">Fabric</a> but it's specially geared towards deployment rather than generic <em>building</em>.</p>
| 1
|
2009-02-13T08:37:06Z
|
[
"python",
"build-process",
"build-automation"
] |
Are there any good build frameworks written in Python?
| 542,289
|
<p>I switched from NAnt to using Python to write build automation scripts. I am curious if whether any build frameworks worth using that are similar to Make, Ant, and NAnt, but, instead, are Python-based. For example, Ruby has Rake. What about Python?</p>
| 14
|
2009-02-12T16:59:28Z
| 3,838,805
|
<p>My Rapid Throughts:
SCons is quite mature and oriented also to other languages (es C++)
Waf is very simlar to ant/maven, so you will prefer it if you are used to ant/maven</p>
<p>Paver is very pythonic oriented, and seems a good option if you do not know how to start.</p>
| 2
|
2010-10-01T11:41:00Z
|
[
"python",
"build-process",
"build-automation"
] |
Are there any good build frameworks written in Python?
| 542,289
|
<p>I switched from NAnt to using Python to write build automation scripts. I am curious if whether any build frameworks worth using that are similar to Make, Ant, and NAnt, but, instead, are Python-based. For example, Ruby has Rake. What about Python?</p>
| 14
|
2009-02-12T16:59:28Z
| 15,874,136
|
<p><a href="http://wiki.python.org" rel="nofollow">The Python wiki</a> maintains a page <a href="http://wiki.python.org/moin/ConfigurationAndBuildTools" rel="nofollow">on python build and deployment tools</a>.</p>
| 1
|
2013-04-08T08:04:06Z
|
[
"python",
"build-process",
"build-automation"
] |
Should I use Django's contrib applications or build my own?
| 542,594
|
<p>The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your requirements.</p>
<p>What do you think?</p>
| 3
|
2009-02-12T18:10:45Z
| 542,685
|
<p>It all depends. We had a need for something that was 98% similar to contrib.flatpages. We could have monkeypatched it, but we decided that the code was so straightforward that we would just copy and fork it. It worked out fine.</p>
<p>Doing this with contrib.auth, on the other hand, might be a bad move given its interaction with contrib.admin & contrib.session.</p>
| 7
|
2009-02-12T18:34:34Z
|
[
"python",
"django",
"django-contrib"
] |
Should I use Django's contrib applications or build my own?
| 542,594
|
<p>The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your requirements.</p>
<p>What do you think?</p>
| 3
|
2009-02-12T18:10:45Z
| 543,335
|
<p>Most of the apps in django.contrib are written very well and are highly extensible.</p>
<p>Don't like quite how comments works? Subclass the models and forms within it, adding your own functionality and you have a working comment system that fits your sites schema, with little effort.</p>
<p>I think the best part when you extend the contrib apps is you're not really doing anything hacky, you're just writing (mostly) regular Python code to add the functionality.</p>
| 4
|
2009-02-12T21:22:15Z
|
[
"python",
"django",
"django-contrib"
] |
Should I use Django's contrib applications or build my own?
| 542,594
|
<p>The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your requirements.</p>
<p>What do you think?</p>
| 3
|
2009-02-12T18:10:45Z
| 549,021
|
<p>I'd also check out third-party re-usable apps before building my own. Many are listed on <a href="http://djangoplugables.com/" rel="nofollow">Django Plug(g)ables</a>, and most are hosted on <a href="http://code.google.com/search/?q=django#q=django" rel="nofollow">Google Code</a>, <a href="http://github.com/search?type=Repositories&language=python&q=django&repo=&langOverride=&x=15&y=15&start_value=1" rel="nofollow">GitHub</a> or <a href="http://bitbucket.org/repo/all/?name=django" rel="nofollow">BitBucket</a>.</p>
| 6
|
2009-02-14T12:10:03Z
|
[
"python",
"django",
"django-contrib"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,610
|
<p>In the comment to the answer that provided this solution:</p>
<blockquote>
<p>"If the file has no extension this incorrectly returns the file name instead of an empty string."</p>
</blockquote>
<p>Not every file has an extension.</p>
| 0
|
2009-02-12T18:15:59Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,611
|
<p>A clearly defined and documented method to get the file extension would always be preferred over splitting a string willy nilly because that method would be more fragile for various reasons.</p>
<p>Edit: This is not language specific.</p>
| 1
|
2009-02-12T18:16:00Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,614
|
<p>os.path.splitext will correctly handle the situation where the file has no extension and return an empty string. .split will return the name of the file.</p>
| 10
|
2009-02-12T18:16:40Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,615
|
<p>The first and most obvious difference is that the split call has no logic in it to default when there is no extension.</p>
<p>This can also be accomplished by a regex, in order to get it to behave as a 1 liner without extra includes, but still return, empty string if the extension isn't there.</p>
<p>Also, the path library can handle different contexts for paths having different seperators for folders.</p>
| 1
|
2009-02-12T18:16:55Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,616
|
<p>There exist operating systems that do not use â.â as an extension separator.</p>
<p>(Notably, RISC OS by convention uses â/â, since â.â is used there as a path separator.)</p>
| 6
|
2009-02-12T18:16:57Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,617
|
<ol>
<li>Right tool for the right job</li>
<li>Already thoroughly debugged and tested as part of the Python standard library - no bugs introduced by mistakes in your hand-rolled version (e.g. what if there is no extension, or the file is a hidden file on UNIX like '.bashrc', or there are multiple extensions?)</li>
<li>Being designed for this purpose, the function has useful return values (basename, ext) for the filename passed, which can be more useful in certain cases versus having to split the path manually (again, edge cases could be a concern when figuring out the basename - ext)</li>
</ol>
<p>The only reason to worry about importing the module is concern for overhead - that's not likely to be a concern in the vast majority of cases, and if it is that tight then it's likely other overhead in Python will be a bigger problem before that.</p>
| 2
|
2009-02-12T18:17:08Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,619
|
<p>Well, there are separate implementations for separate operating systems. This means that if the logic to extract the extension of a file differs on Mac from that on Linux, this distinction will be handled by those things. I don't know of any such distinction so there might be none.</p>
<p><hr /></p>
<p><strong>Edit</strong>: <a href="http://stackoverflow.com/users/9493/brian">@Brian</a> comments that an example like <code>/directory.ext/file</code> would of course not work with a simple <code>.split('.')</code> call, and you would have to know both that directories can use extensions, as well as the fact that on some operating systems, forward slash is a valid directory separator.</p>
<p>This just emphasizes the <em>use a library routine unless you have a good reason not to</em> part of my answer.</p>
<p>Thanks <a href="http://stackoverflow.com/users/9493/brian">@Brian</a>.</p>
<p><hr /></p>
<p>Additionally, where a file doesn't have an extension, you would have to build in logic to handle that case. And what if the thing you try to split is a directory name ending with a backslash? No filename nor an extension.</p>
<p>The rule should be that unless you have a specific reason not to use a library function that does what you want, use it. This will avoid you having to maintain and bugfix code others have perfectly good solutions to.</p>
| 28
|
2009-02-12T18:17:46Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,621
|
<p><code>splitext()</code> does a reverse search for '.' and returns the extension portion as soon as it finds it. <code>split('.')</code> will do a forward search for all '.' characters and is therefore almost always slower. In other words <code>splitext()</code> is specifically written for returning the extension unlike <code>split()</code>.</p>
<p>(see posixpath.py in the Python source if you want to examine the implementation).</p>
| 8
|
2009-02-12T18:18:16Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 542,643
|
<p>Besides being standard and therefore guaranteed to be available, <code>os.path.splitext</code>:</p>
<p><strong>Handles edge cases</strong> - like that of a missing extension.<br />
<strong>Offers guarantees</strong> - Besides correctly returning the extension if one exists, it guarantees that <code>root</code> + <code>ext</code> will always return the full path.<br />
<strong>Is cross-platform</strong> - in the Python source there are actually three different version of os.path, and they are called based on which operating system Python thinks you are on.<br />
<strong>Is more readable</strong> - consider that your version requires users to know that arrays can be indexed with negative numbers. </p>
<p>btw, it should not be any faster. </p>
| 0
|
2009-02-12T18:23:06Z
|
[
"python"
] |
Benefits of os.path.splitext over regular .split?
| 542,596
|
<p>In <a href="http://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python">this other question</a>, the votes clearly show that the <code>os.path.splitext</code> function is preferred over the simple <code>.split('.')[-1]</code> string manipulation. Does anyone have a moment to explain exactly why that is? Is it faster, or more accurate, or what? I'm willing to accept that there's something better about it, but I can't immediately see what it might be. Might importing a whole module to do this be overkill, at least in simple cases?</p>
<p>EDIT: The OS specificity is a big win that's not immediately obvious; but even I should've seen the "what if there isn't a dot" case! And thanks to everybody for the general comments on library usage.</p>
| 23
|
2009-02-12T18:10:51Z
| 545,368
|
<p>1) simple split('.')[-1] won't work correctly for the path as C:\foo.bar\Makefile so you need to extract basename first with os.path.basename(), and even in this case it will fail to split file without extension correctly. os.path.splitext do this under the hood.</p>
<p>2) Despite the fact os.path.splitext is cross-platform solution it's not ideal. Let's looking at the special files with leading dot, e.g. .cvsignore, .bzrignore, .hgignore (they are very popular in some VCS as special files). os.path.splitext will return entire file name as extension, although it does not seems right for me. Because in this case name without extension is empty string. Although this is intended behavior of Python standard library, it's may be not what user wants actually.</p>
| 0
|
2009-02-13T09:44:25Z
|
[
"python"
] |
Help needed to convert code from C# to Python
| 542,908
|
<p>Can you please convert this code from C# to Python to be run on IronPython?</p>
<p>I donât have any experience with Python.</p>
<pre><code>using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Connect("127.0.0.1", 1234);
foo.Add(bar);
bar.Ready += new Agent.ReadyHandler(bar_Ready);
}
static void bar_Ready(object sender, string msg)
{
Console.WriteLine(msg.body);
}
}
}
</code></pre>
| 0
|
2009-02-12T19:42:23Z
| 542,939
|
<p>I think it would suit you best if you take a look at the following links:</p>
<p><a href="http://www.learningpython.com/2006/10/02/ironpython-hello-world-tutorial/" rel="nofollow">http://www.learningpython.com/2006/10/02/ironpython-hello-world-tutorial/</a>
<a href="http://msdn.microsoft.com/en-us/magazine/cc300810.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/cc300810.aspx</a></p>
| 1
|
2009-02-12T19:51:16Z
|
[
"c#",
".net",
"python",
"ironpython"
] |
Help needed to convert code from C# to Python
| 542,908
|
<p>Can you please convert this code from C# to Python to be run on IronPython?</p>
<p>I donât have any experience with Python.</p>
<pre><code>using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Connect("127.0.0.1", 1234);
foo.Add(bar);
bar.Ready += new Agent.ReadyHandler(bar_Ready);
}
static void bar_Ready(object sender, string msg)
{
Console.WriteLine(msg.body);
}
}
}
</code></pre>
| 0
|
2009-02-12T19:42:23Z
| 542,942
|
<p>Instantiation doesn't require a type definition. Methods called the same, assign delegates directly. The previous answer is absolutely right, you'll need a <strong>lot</strong> more context in order to "convert" a C# application to Python; it's more than just syntax.</p>
<pre><code>foo = Portal("Foo")
bar = Agent("bar")
foo.Connect("ip", 1234)
foo.Add(bar)
bar.Ready = bar_Ready
def bar_Ready(sender, msg):
print msg.body
</code></pre>
| 5
|
2009-02-12T19:52:06Z
|
[
"c#",
".net",
"python",
"ironpython"
] |
Help needed to convert code from C# to Python
| 542,908
|
<p>Can you please convert this code from C# to Python to be run on IronPython?</p>
<p>I donât have any experience with Python.</p>
<pre><code>using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Connect("127.0.0.1", 1234);
foo.Add(bar);
bar.Ready += new Agent.ReadyHandler(bar_Ready);
}
static void bar_Ready(object sender, string msg)
{
Console.WriteLine(msg.body);
}
}
}
</code></pre>
| 0
|
2009-02-12T19:42:23Z
| 2,958,339
|
<p>Or if you're feeling really lazy, there's a <a href="http://www.developerfusion.com/tools/convert/csharp-to-python/" rel="nofollow">C# to Python converter</a> on developer fusion!</p>
| 2
|
2010-06-02T13:52:47Z
|
[
"c#",
".net",
"python",
"ironpython"
] |
Help needed to convert code from C# to Python
| 542,908
|
<p>Can you please convert this code from C# to Python to be run on IronPython?</p>
<p>I donât have any experience with Python.</p>
<pre><code>using System;
using Baz;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Portal foo = new Portal("Foo");
Agent bar = new Agent("Bar");
foo.Connect("127.0.0.1", 1234);
foo.Add(bar);
bar.Ready += new Agent.ReadyHandler(bar_Ready);
}
static void bar_Ready(object sender, string msg)
{
Console.WriteLine(msg.body);
}
}
}
</code></pre>
| 0
|
2009-02-12T19:42:23Z
| 4,208,936
|
<p>In case someone else has this question SharpDevelop has a conversion utility to convert between C# and IronPython, VB.NET or Boo
<a href="http://community.sharpdevelop.net/blogs/mattward/archive/2009/05/11/ConvertingCSharpVBNetCodeToIronPython.aspx" rel="nofollow">http://community.sharpdevelop.net/blogs/mattward/archive/2009/05/11/ConvertingCSharpVBNetCodeToIronPython.aspx</a></p>
| 0
|
2010-11-17T20:40:08Z
|
[
"c#",
".net",
"python",
"ironpython"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 543,521
|
<p>Stop gap solution:</p>
<pre><code>:imap ( ()<C-[>i
</code></pre>
<p>This will make it so every time you type a left paren it will automatically put in the right and put you in the position of typing in between.</p>
| 3
|
2009-02-12T21:52:21Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 543,554
|
<p>You can get vim to do the opposite: do a </p>
<blockquote>
<p>:set showmatch</p>
</blockquote>
<p>and it will highlight matching parens. You'll know when you're unbalanced when it doesn't highlight something.</p>
<p>I'm also assuming you're familiar with the '%' command, which bounces you to the matching element.</p>
| 8
|
2009-02-12T21:55:23Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 543,881
|
<p>Not sure if it'll be more or less confusing for you, but you could look at the <code>lisp.vim</code> syntax file (especially the part where <code>g:lisp_rainbow</code> is handled) to see how you can highlight matching parens.</p>
<p>If you manage to highlight all the matching parens, you could have the leftover parens (i.e. unmatched parens) have default Error highlighting. This is what the lisp file seems to be doing.</p>
<h3>EDIT: How about this:</h3>
<pre><code>syn match parenError ")"
syn region matchingParens transparent start="(" end=")" contains=matchingParens
hi parenError guifg=red
</code></pre>
<p>If you <code>:syn clear</code> and run those, it seems to work. Note that the order the <code>syn</code> commands are executed matters. Per <code>:h :syn-priority</code>, the rule matched <strong>last</strong> is the one that takes effect, which may be why your rules highlighted all the end-parens in the file.</p>
<h3>EDIT #2:</h3>
<p>What c.vim is actually doing is highlighting <strong>any</strong> <code>{}</code> inside of <code>()</code>, whether everything is properly closed or not. Try typing <code>({})</code> in C mode, it still highlights the <code>{}</code> as an error. </p>
<p>I don't think this approach can be used to test directly for a <code>(</code> with an unmatched <code>)</code>, because <code>:syn region</code> doesn't care whether the end-pattern is there or not.</p>
<p>So you have to find something Python-specific that should never belong inside <code>()</code>. Then match against <code>"(\_[^)]*the_forbidden_something"</code>. I don't know Python enough to know what that might be.</p>
<p>If nothing else, you can do:</p>
<pre><code>syn match openParen "(\_[^)]*\%$"
</code></pre>
<p>which matches an open paren with no closing parens before the end-of-file. This fails if it finds any closing paren at all, which means it won't even catch <code>(()<EOF></code>.</p>
| 2
|
2009-02-12T22:54:55Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 566,124
|
<p>As a workaround, I found <a href="http://www.vim.org/scripts/script.php?script_id=974" rel="nofollow">this indent script</a> on the vim website that supposedly does a better job of indenting Python code. When you end a line with unbalanced parens, it indents the next line to line up with the open paren.</p>
| 0
|
2009-02-19T16:33:47Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 602,453
|
<p>If I understand correctly and you are trying to look at non-matching parenthesis in C code (that was generated in python), I would recommend you install rainbow.vim from <a href="http://www.drchip.org/astronaut/vim/#RAINBOW" rel="nofollow">Dr Chip's Site</a>. This will highlight braces in different colours depending on the levels of indentation and will highlight unmatching braces in red as you have requested. A screenshot <img src="http://img294.imageshack.us/img294/8586/rainbow.jpg" alt="http://img294.imageshack.us/img294/8586/rainbow.jpg" title="Rainbow Brace Error"></p>
<p>To install, download <strong><code>rainbow.vim</code></strong> and place in <code>vimfiles/after/syntax/c/</code> (create this directory if it is not present).</p>
<p>On Linux, this will be <code>~/.vim/after/syntax/c/rainbow.vim</code></p>
<p>On Windows, it may be <code>c:\vim\vimfiles\after\syntax\c\rainbow.vim</code> or possibly somewhere else, see <code>:help runtimepath</code>.</p>
<p>Note that there are some plugins that conflict with <code>rainbow.vim</code>, but it's not too hard to make them co-operate.</p>
<p>If you are trying to highlight non-matching parenthesis in the python code, you could modify rainbow.vim to use the python syntax clusters instead of the C ones, but this is a little more involved, but you could use something along the lines of (modified version of Dr Chip's rainbow code):</p>
<pre><code>syn cluster pyParenGroup contains=pythonString,pythonRawString,pythonEscape,pythonNumber,pythonBuiltin,pythonException
syn match pyParenError display ')'
syn region pyParen transparent matchgroup=hlLevel0 start='(' end=')' contains=@pyParenGroup,pyParen1
syn region pyParen1 transparent matchgroup=hlLevel1 start='(' end=')' contains=@pyParenGroup,pyParen2
syn region pyParen2 transparent matchgroup=hlLevel2 start='(' end=')' contains=@pyParenGroup,pyParen3
syn region pyParen3 transparent matchgroup=hlLevel3 start='(' end=')' contains=@pyParenGroup,pyParen4
syn region pyParen4 transparent matchgroup=hlLevel4 start='(' end=')' contains=@pyParenGroup,pyParen5
syn region pyParen5 transparent matchgroup=hlLevel5 start='(' end=')' contains=@pyParenGroup,pyParen6
syn region pyParen6 transparent matchgroup=hlLevel6 start='(' end=')' contains=@pyParenGroup,pyParen7
syn region pyParen7 transparent matchgroup=hlLevel7 start='(' end=')' contains=@pyParenGroup,pyParen8
syn region pyParen8 transparent matchgroup=hlLevel8 start='(' end=')' contains=@pyParenGroup,pyParen9
syn region pyParen9 transparent matchgroup=hlLevel9 start='(' end=')' contains=@pyParenGroup,pyParen
hi link pyParenError Error
if &bg == "dark"
hi default hlLevel0 ctermfg=red guifg=red1
hi default hlLevel1 ctermfg=yellow guifg=orange1
hi default hlLevel2 ctermfg=green guifg=yellow1
hi default hlLevel3 ctermfg=cyan guifg=greenyellow
hi default hlLevel4 ctermfg=magenta guifg=green1
hi default hlLevel5 ctermfg=red guifg=springgreen1
hi default hlLevel6 ctermfg=yellow guifg=cyan1
hi default hlLevel7 ctermfg=green guifg=slateblue1
hi default hlLevel8 ctermfg=cyan guifg=magenta1
hi default hlLevel9 ctermfg=magenta guifg=purple1
else
hi default hlLevel0 ctermfg=red guifg=red3
hi default hlLevel1 ctermfg=darkyellow guifg=orangered3
hi default hlLevel2 ctermfg=darkgreen guifg=orange2
hi default hlLevel3 ctermfg=blue guifg=yellow3
hi default hlLevel4 ctermfg=darkmagenta guifg=olivedrab4
hi default hlLevel5 ctermfg=red guifg=green4
hi default hlLevel6 ctermfg=darkyellow guifg=paleturquoise3
hi default hlLevel7 ctermfg=darkgreen guifg=deepskyblue4
hi default hlLevel8 ctermfg=blue guifg=darkslateblue
hi default hlLevel9 ctermfg=darkmagenta guifg=darkviolet
endif
</code></pre>
<p>EDIT:</p>
<p>As a test, I downloaded <strong>gvim70.zip</strong> and <strong>vim70rt.zip</strong> from <a href="ftp://ftp.vim.org/pub/vim/pc/" rel="nofollow">ftp://ftp.vim.org/pub/vim/pc/</a> (these are the Windows versions of Vim 7.0). I unzipped the two files into a new directory and ran <code>gvim.exe</code> from <code>vim/vim70/gvim.exe</code>. I <strong>do not</strong> have any vim configuration stored in "C:\Documents and Settings", so running this vim is the same as running a 'vanilla' configuration. I then downloaded <code>pyprint.py</code> from <a href="http://www.amk.ca/python/simple/pyprint.html" rel="nofollow">amk.ca/python/simple/pyprint.html</a> as a piece of sample code and copied the above code into a file called code.vim. In gVim, I entered <code>:e pyprint.py</code>. It opened in the white-background window, with no syntax highlighting. I then entered <code>:syntax on</code>, which switched the default syntax highlighting on. I added a second <code>)</code> character on line 8. Finally, I entered <code>:source code.vim</code>, which made the second <code>)</code> character be highlighted in red.</p>
<p>I've also carried out this test on Linux (with Vim 7.2), by entering the following command sequence:</p>
<pre><code>cd ~
mv .vimrc old_dot_vimrc
mv .gvimrc old_dot_gvimrc
mv .vim old_dot_vim
vim pyprint.py
:e pyprint.py
" Add extra bracket here!
:syntax on
:source code.vim
</code></pre>
<p>Again, the second bracket is highlighted and everything else seems normal.</p>
| 5
|
2009-03-02T14:07:48Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 602,601
|
<p>Have you tried using <a href="http://www.vim.org/scripts/script.php?script%5Fid=39" rel="nofollow" title="matchit.vim">matchit.vim</a>? It supports all sorts of matches, and it <em>should</em> work in Python.</p>
| 1
|
2009-03-02T14:51:30Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Highlighting unmatched brackets in vim
| 542,929
|
<p>I'm getting burned repeatedly by unmatched parentheses while writing python code in vim. I like how they're handled for C code - vim highlights in red all of the curly braces following the unmatched paren. I looked at the <code>c.vim</code> syntax file briefly to try to understand it, but the section that handles bracket errors is very complex. Can anyone explain how that code works and suggest how I might write something similar for python code?</p>
<p>Example C code with unmatched parens:</p>
<pre><code>int main(void
{ /* brace highlighted in red */
} /* brace highlighted in red */
</code></pre>
<p>Since python code doesn't have curly braces to highlight, we'll have to choose something else (perhaps other parentheses).</p>
<p>BTW, I tried out <a href="http://www.vim.org/scripts/script.php?script_id=350">this vim plugin</a> but I wasn't happy with the behavior.</p>
<p>Edit:</p>
<p>I'm using python to generate C++ code (a language that likes parentheses and semicolons). I have a nasty habit of leaving the trailing paren off a <code>file.write()</code> method call. It would be nice if I could get vim to make that mistake more visually obvious.</p>
<p><strong>Update:</strong></p>
<p>Ok, here's what I've tried so far.</p>
<pre><code>:syn region pParen transparent start="(" end=")" contains=ALL
:syn match pError display ")"
:hi def link pError Error
</code></pre>
<p>Unfortunately, all this does is highlight as an error the right paren of all <strong>balanced</strong> parentheses, the opposite of what I want to do. I really don't understand what I'm doing here (just copied off of the existing C syntax file). If anyone could explain what I did (wrong), I would appreciate it.</p>
| 11
|
2009-02-12T19:47:23Z
| 37,886,090
|
<p>The plugin <a href="https://github.com/arnar/vim-matchopen" rel="nofollow">vim-matchopen</a> does what you are looking for</p>
<p><img src="http://i.imgur.com/wmSvzRm.png" alt=""><br>
The highlight color changes based on your colorscheme</p>
| 0
|
2016-06-17T16:15:19Z
|
[
"python",
"vim",
"syntax-highlighting"
] |
Invoking built-in operators indirectly in Python
| 542,987
|
<p>Let's say you have a small calculator program that takes numbers and an operator to perform on those numbers as input, then prints out the result of applying the specified operation. So if you input "4 + 5" it will print out "9". Simple, right? Well what I want to be able to write is something this:</p>
<pre><code>a, op, b = raw_input().split()
print somehowInvokeOperator(op, a, b)
</code></pre>
<p>The problem is that "somehowInvokeOperator()" part. Is there anyway to do this without resorting to either (a) eval() or (b) some type of dictionary mapping keys like "+" and "-" to functions that perform the appropriate operation? getattr() doesn't appear to work for this. I don't really need this code for anything, I'm just curious to see if this can be solved in Python as elegantly as it can in other dynamic languages.</p>
| 2
|
2009-02-12T20:01:23Z
| 542,996
|
<p>If you really wanted to do this, you would need the standard <code>operator</code> module. See also <a href="http://docs.python.org/reference/datamodel.html#object.__add__" rel="nofollow">Emulating numeric types</a>. And, yes, a dictionary full of functions would be a perfectly sound dynamic way to make this happen.</p>
<pre><code>import operator
operations = {'+' : operator.add}
result = operations[op](a, b)
</code></pre>
| 2
|
2009-02-12T20:03:17Z
|
[
"python"
] |
Invoking built-in operators indirectly in Python
| 542,987
|
<p>Let's say you have a small calculator program that takes numbers and an operator to perform on those numbers as input, then prints out the result of applying the specified operation. So if you input "4 + 5" it will print out "9". Simple, right? Well what I want to be able to write is something this:</p>
<pre><code>a, op, b = raw_input().split()
print somehowInvokeOperator(op, a, b)
</code></pre>
<p>The problem is that "somehowInvokeOperator()" part. Is there anyway to do this without resorting to either (a) eval() or (b) some type of dictionary mapping keys like "+" and "-" to functions that perform the appropriate operation? getattr() doesn't appear to work for this. I don't really need this code for anything, I'm just curious to see if this can be solved in Python as elegantly as it can in other dynamic languages.</p>
| 2
|
2009-02-12T20:01:23Z
| 543,029
|
<p>Basically no, you will at least need to have a dictionary or function to map operator characters to their implementations. It's actually a little more complicated than that, since not all operators take the form <code>a [op] b</code>, so in general you'd need to do a bit of parsing; see <a href="https://docs.python.org/library/operator.html" rel="nofollow">https://docs.python.org/library/operator.html</a> for the full list of correspondences, and for the functions you'll probably want to use for the operator implementations.</p>
<p>If you're only trying to implement the binary arithmetic operators like + - * / % ** then a dictionary should be good enough.</p>
| 6
|
2009-02-12T20:10:19Z
|
[
"python"
] |
Invoking built-in operators indirectly in Python
| 542,987
|
<p>Let's say you have a small calculator program that takes numbers and an operator to perform on those numbers as input, then prints out the result of applying the specified operation. So if you input "4 + 5" it will print out "9". Simple, right? Well what I want to be able to write is something this:</p>
<pre><code>a, op, b = raw_input().split()
print somehowInvokeOperator(op, a, b)
</code></pre>
<p>The problem is that "somehowInvokeOperator()" part. Is there anyway to do this without resorting to either (a) eval() or (b) some type of dictionary mapping keys like "+" and "-" to functions that perform the appropriate operation? getattr() doesn't appear to work for this. I don't really need this code for anything, I'm just curious to see if this can be solved in Python as elegantly as it can in other dynamic languages.</p>
| 2
|
2009-02-12T20:01:23Z
| 543,146
|
<p>Warning: this is not pythonic at all!! (goes against every rule of the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Python</a>!)</p>
<p>Here's a <em>magical</em>, one-liner dictionary:</p>
<pre><code>ops = eval( '{%s}'%','.join([('\''+op + '\' : lambda a,b: a ' + op + ' b') for op in '+-*/%']) )
</code></pre>
<p>That defines your dictionary .. which you can use</p>
<pre><code>ops['+'](10,4) #returns 14
</code></pre>
<p>the basic idea is mapping each operator to a lambda function:</p>
<pre><code>{ '+' : lambda a,b: a + b }
</code></pre>
| 2
|
2009-02-12T20:42:14Z
|
[
"python"
] |
two questions (RFC822, login info) about sending email via python
| 543,096
|
<h1>1 -</h1>
<p>In my email-sending script, I store spaced-out emails in a string, then I use ", ".join(to.split()). However, it looks like the script only sends to the 1st email - is it something to do with RFC822 format? If so, how can I fix this? </p>
<h1>2 -</h1>
<p>I feel a bit edgy having my password visable in my script. Is there a way to retrieve this info from cookies or saved passwords from firefox?</p>
<p>Thanks in advance!</p>
| -2
|
2009-02-12T20:31:56Z
| 545,517
|
<p>Use <code>', '.join()</code> for the list in the <code>To:</code> or <code>Cc:</code> header, but the headers are only for show. What determines where the mail actually goes is the RCPT envelope. Assuming you're using smtplib, that's the second argument:</p>
<pre><code>connection.sendmail(senderaddress, to.split(), mailtext)
</code></pre>
<p>2: it's possible, but far from straightforward. Browsers don't want external programs looking at their security-sensitive stored data.</p>
| 3
|
2009-02-13T10:40:48Z
|
[
"python",
"smtp",
"passwords",
"rfc822"
] |
two questions (RFC822, login info) about sending email via python
| 543,096
|
<h1>1 -</h1>
<p>In my email-sending script, I store spaced-out emails in a string, then I use ", ".join(to.split()). However, it looks like the script only sends to the 1st email - is it something to do with RFC822 format? If so, how can I fix this? </p>
<h1>2 -</h1>
<p>I feel a bit edgy having my password visable in my script. Is there a way to retrieve this info from cookies or saved passwords from firefox?</p>
<p>Thanks in advance!</p>
| -2
|
2009-02-12T20:31:56Z
| 546,364
|
<p>For the second part of your question, you could take a look at the netrc module (<a href="http://docs.python.org/library/netrc.html" rel="nofollow">http://docs.python.org/library/netrc.html</a>).</p>
<p>This isn't much better than having the password in the script, but it does allow the script to be readable for anyone using the computer, while you have the password in a file in your home directory that is only readable by you.</p>
| 2
|
2009-02-13T15:30:45Z
|
[
"python",
"smtp",
"passwords",
"rfc822"
] |
Granularity of Paradigm Mixing
| 543,140
|
<p>When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?</p>
| 2
|
2009-02-12T20:41:14Z
| 543,166
|
<p>Different paradigms mix in different ways. For example, Using OOP doesn't eliminate the use of subroutines and procedural code from an outside library. It merely moves the procedures around into a different place.</p>
<p>It is impossible to purely program with one paradigm. You may think you have a single one in mind when you program, but that's your illusion. Your resultant code will land along the borders and within the bounds of many paradigms.</p>
| 2
|
2009-02-12T20:47:40Z
|
[
"python",
"ruby",
"coding-style"
] |
Granularity of Paradigm Mixing
| 543,140
|
<p>When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?</p>
| 2
|
2009-02-12T20:41:14Z
| 579,842
|
<p>I am not sure that I ever think about it like this. </p>
<p>Once you start "thinking in Ruby" the multi-paradigms just merge into ... well, Ruby. </p>
<p>Ruby is object-oriented, but I find that other things such as the functional aspect tend to mean that some of the "traditional" design patters present in OO languages are just simply not relevant. The iterator is a classic example ... iteration is something that is handled elegantly in Ruby and the heavy-weight OO iteration patterns no longer really apply. This seems to be true throughout the language.</p>
| 2
|
2009-02-23T23:23:48Z
|
[
"python",
"ruby",
"coding-style"
] |
Granularity of Paradigm Mixing
| 543,140
|
<p>When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?</p>
| 2
|
2009-02-12T20:41:14Z
| 583,881
|
<p>Mixing paradigms has an advantage of letting you express solutions in most natural and esy way. Which is very good thing when it help keeping your program logic smaller. For example, filtering a list by some criteria is several times simpler to express with functional solution compared to traditional loop.</p>
<p>On the other hand, to get benefit from mixing two or more paradigms programmer should be reasonably fluent with all of them. So this is powerful tool that should be used with care. </p>
| 1
|
2009-02-24T22:21:02Z
|
[
"python",
"ruby",
"coding-style"
] |
Granularity of Paradigm Mixing
| 543,140
|
<p>When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?</p>
| 2
|
2009-02-12T20:41:14Z
| 622,514
|
<p>Different problems require different solutions, but it helps if you solve things the same way in the same layer. And varying to wildly will just confuse you and everyone else in the project.</p>
<p>For C++, I've found that statically typed OOP (use zope.interface in Python) work well for higher-level parts (connecting, updating, signaling, etc) and functional stuff solves many lower-level problems (parsing, nuts 'n bolts data processing, etc) more nicely. </p>
<p>And usually, a dynamically typed scripting system is good for selecting and configuring the specific app, game level, whatnot. This may be the language itself (i.e. Python) or something else (an xml-script engine + necessary system for dynamic links in C++). </p>
| 0
|
2009-03-07T21:10:58Z
|
[
"python",
"ruby",
"coding-style"
] |
How do I attach a remote debugger to a Python process?
| 543,196
|
<p>I'm tired of inserting</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface?</p>
| 47
|
2009-02-12T20:54:08Z
| 543,258
|
<p>Well, you can get something quite similar to that using a twisted manhole, which
works like this:</p>
<pre><code>from twisted.internet import reactor
from twisted.cred import portal, checkers
from twisted.conch import manhole, manhole_ssh
def getManholeFactory(namespace):
realm = manhole_ssh.TerminalRealm()
def getManhole(_):
return manhole.Manhole(namespace)
realm.chainedProtocolFactory.protocolFactory = getManhole
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUsernamePassword DatabaseDontUse(admin='foobar'))
f = manhole_ssh.ConchFactory(p)
return f
reactor.listenTCP(2222, getManholeFactory(globals()))
reactor.run()
</code></pre>
<p>Then you just login to the program over ssh;</p>
<pre><code>$ ssh admin@localhost -p 2222
admin@localhost's password:
</code></pre>
<p>Using <strong>foobar</strong> as the password.</p>
<p>When you login you'll get a normal python prompt where you can just poke at the data.
It's not quite the same as getting a traceback sent over to a host.</p>
<p>Now, this might be tricky to integrate to a GUI program, in that case you might need to choose another reactor, for instance for gtk based programs used the gtk2reactor etc.</p>
<p>If you want the actual traceback sent over you need to create a socket channel for both stderr, stdin and stdout which goes over the network instead of printing to your local host. Shouldn't be too hard to accomplish by using twisted.</p>
| 16
|
2009-02-12T21:07:19Z
|
[
"python",
"remote-debugging"
] |
How do I attach a remote debugger to a Python process?
| 543,196
|
<p>I'm tired of inserting</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface?</p>
| 47
|
2009-02-12T20:54:08Z
| 544,838
|
<p>use <a href="http://winpdb.org/">Winpdb</a>. It is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p>
<p>Features:</p>
<ul>
<li>GPL license. Winpdb is Free Software.</li>
<li>Compatible with CPython 2.3 through 2.6 and Python 3000</li>
<li>Compatible with wxPython 2.6 through 2.8</li>
<li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li>
<li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li>
</ul>
<p><img src="http://winpdb.org/images/screenshot_winpdb_small.jpg" alt="Screenshot" /></p>
| 56
|
2009-02-13T05:32:18Z
|
[
"python",
"remote-debugging"
] |
How do I attach a remote debugger to a Python process?
| 543,196
|
<p>I'm tired of inserting</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface?</p>
| 47
|
2009-02-12T20:54:08Z
| 28,813,615
|
<p>Two solutions from modern IDEs:</p>
<ol>
<li><p>PTVS cross-platform remote debugging</p></li>
<li><p>PyCharm/PyDev remote debugging</p></li>
</ol>
| 1
|
2015-03-02T15:37:29Z
|
[
"python",
"remote-debugging"
] |
How do I attach a remote debugger to a Python process?
| 543,196
|
<p>I'm tired of inserting</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface?</p>
| 47
|
2009-02-12T20:54:08Z
| 29,451,814
|
<p>A little bit late, but here is a very lightweight remote debugging solution courtesy of <a href="http://michaeldehaan.net/post/35403909347/tips-on-using-debuggers-with-ansible">http://michaeldehaan.net/post/35403909347/tips-on-using-debuggers-with-ansible</a>:</p>
<ol>
<li><code>pip install epdb</code> on the remote host.</li>
<li>Make sure your firewalling setup is not allowing non-local connections to port 8080 on the remote host, since <code>epdb</code> defaults to listening on any address (<code>INADDR_ANY</code>), not 127.0.0.1.</li>
<li>Instead of using <code>import pdb; pdb.set_trace()</code> in your program, use <code>import epdb; epdb.serve()</code>.</li>
<li>Securely log in to the remote host, since <code>epdb.connect()</code> uses telnet.</li>
<li>Attach to the program using <code>python -c "import epdb; epdb.connect()</code>.</li>
</ol>
<p>Adjust the security bits to suite your local network setup and security stance, of course.</p>
| 5
|
2015-04-04T21:55:19Z
|
[
"python",
"remote-debugging"
] |
Add Quotes in url string from file
| 543,199
|
<p>I need script to add quotes in url string from url.txt</p>
<p>from <code>http://www.site.com/info.xx</code> to <code>"http://www.site.com/info.xx"</code></p>
| 2
|
2009-02-12T20:54:42Z
| 543,210
|
<pre><code>url = '"%s"' % url
</code></pre>
<p>Example:</p>
<pre><code>line = 'http://www.site.com/info.xx \n'
url = '"%s"' % line.strip()
print url # "http://www.site.com/info.xx"
</code></pre>
<p>Remember, adding a backslash before a quotation mark will escape it and therefore won't end the string.</p>
| 7
|
2009-02-12T20:57:35Z
|
[
"python",
"ruby",
"perl"
] |
Add Quotes in url string from file
| 543,199
|
<p>I need script to add quotes in url string from url.txt</p>
<p>from <code>http://www.site.com/info.xx</code> to <code>"http://www.site.com/info.xx"</code></p>
| 2
|
2009-02-12T20:54:42Z
| 543,218
|
<p>write one...<br />
perl is my favourite scripting language... it appears you may prefer Python.</p>
<p>just read in the file and add \" before and after it..<br />
this is pretty easy in perl.</p>
<p>this seems more like a request than a question... should this be on stackoverflow?</p>
| 0
|
2009-02-12T20:59:12Z
|
[
"python",
"ruby",
"perl"
] |
Add Quotes in url string from file
| 543,199
|
<p>I need script to add quotes in url string from url.txt</p>
<p>from <code>http://www.site.com/info.xx</code> to <code>"http://www.site.com/info.xx"</code></p>
| 2
|
2009-02-12T20:54:42Z
| 543,229
|
<pre><code>url = '"%s"' % url
</code></pre>
<p>Example:</p>
<pre><code>>>> url = "http://www.site.com/info.xx"
>>> print url
http://www.site.com/info.xx
>>> url = '"%s"' % url
>>> print url
"http://www.site.com/info.xx"
>>>
</code></pre>
<p>Parsing it from a file:</p>
<pre><code>from __future__ import with_statement
def parseUrlsTXT(filename):
with open(filename, 'r') as f:
for line in f.readlines():
url = '"%s"' % line[:-1]
print url
</code></pre>
<p>Usage:</p>
<pre><code>parseUrlsTXT('/your/dir/path/URLs.txt')
</code></pre>
| 4
|
2009-02-12T21:00:20Z
|
[
"python",
"ruby",
"perl"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.