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
sequence |
---|---|---|---|---|---|---|---|---|---|
How do you return multiple values in Python? | 354,883 | <p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p>
<h3>Option: Using a tuple</h3>
<p>Consider this trivial example:</p>
<pre><code>def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0,y1,y2)
</code></pre>
<p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p>
<h3>Option: Using a dictionary</h3>
<p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p>
<p>Consider the following:</p>
<pre><code>def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
</code></pre>
<p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p>
<p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p>
<pre><code>result['y0']
</code></pre>
<h3>Option: Using a class</h3>
<p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p>
<pre><code>class ReturnValue(object):
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code></pre>
<p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p>
<p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p>
<pre><code>class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
</code></pre>
<p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p>
<blockquote>
<p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p>
</blockquote>
<h3>Option: Using a list</h3>
<p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p>
<pre><code>def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
</code></pre>
<p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p>
<h1>Question</h1>
<p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p>
<p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p>
<p>So, how do -you- return multiple values in Python?</p>
| 435 | 2008-12-10T01:55:50Z | 18,218,465 | <p>Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use <code>struct</code> for data-only items and <code>class</code> for objects with methods, even though you can legally put methods on a <code>struct</code>; my habit is similar in Python, with <code>dict</code> and <code>tuple</code> in place of <code>struct</code>.</p>
<p>For coordinate sets, I'll use a <code>tuple</code> rather than a point <code>class</code> or a <code>dict</code> (and note that you can use a <code>tuple</code> as a dictionary key, so <code>dict</code>s make great sparse multidimensional arrays). </p>
<p>If I'm going to be iterating over a list of things, I prefer unpacking <code>tuple</code>s on the iteration:</p>
<pre><code>for score,id,name in scoreAllTheThings():
if score > goodScoreThreshold:
print "%6.3f #%6d %s"%(score,id,name)
</code></pre>
<p>...as the object version is more cluttered to read:</p>
<pre><code>for entry in scoreAllTheThings():
if entry.score > goodScoreThreshold:
print "%6.3f #%6d %s"%(entry.score,entry.id,entry.name)
</code></pre>
<p>...let alone the <code>dict</code>.</p>
<pre><code>for entry in scoreAllTheThings():
if entry['score'] > goodScoreThreshold:
print "%6.3f #%6d %s"%(entry['score'],entry['id'],entry['name'])
</code></pre>
<p>If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods. </p>
<p>Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a <code>dict</code> because that's best suited to JSON serialization. </p>
| 5 | 2013-08-13T20:18:55Z | [
"python",
"coding-style",
"return",
"return-value"
] |
How do you return multiple values in Python? | 354,883 | <p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p>
<h3>Option: Using a tuple</h3>
<p>Consider this trivial example:</p>
<pre><code>def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0,y1,y2)
</code></pre>
<p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p>
<h3>Option: Using a dictionary</h3>
<p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p>
<p>Consider the following:</p>
<pre><code>def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
</code></pre>
<p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p>
<p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p>
<pre><code>result['y0']
</code></pre>
<h3>Option: Using a class</h3>
<p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p>
<pre><code>class ReturnValue(object):
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code></pre>
<p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p>
<p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p>
<pre><code>class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
</code></pre>
<p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p>
<blockquote>
<p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p>
</blockquote>
<h3>Option: Using a list</h3>
<p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p>
<pre><code>def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
</code></pre>
<p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p>
<h1>Question</h1>
<p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p>
<p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p>
<p>So, how do -you- return multiple values in Python?</p>
| 435 | 2008-12-10T01:55:50Z | 21,970,184 | <p>Another option would be using generators:</p>
<pre><code>>>> def f(x):
y0 = x + 1
yield y0
yield x * 3
yield y0 ** 4
>>> a, b, c = f(5)
>>> a
6
>>> b
15
>>> c
1296
</code></pre>
<p>Although IMHO tuples are usually best, except in cases where the values being returned are candidates for encapsulation in a class.</p>
| 13 | 2014-02-23T15:26:30Z | [
"python",
"coding-style",
"return",
"return-value"
] |
How do you return multiple values in Python? | 354,883 | <p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p>
<h3>Option: Using a tuple</h3>
<p>Consider this trivial example:</p>
<pre><code>def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0,y1,y2)
</code></pre>
<p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p>
<h3>Option: Using a dictionary</h3>
<p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p>
<p>Consider the following:</p>
<pre><code>def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
</code></pre>
<p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p>
<p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p>
<pre><code>result['y0']
</code></pre>
<h3>Option: Using a class</h3>
<p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p>
<pre><code>class ReturnValue(object):
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code></pre>
<p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p>
<p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p>
<pre><code>class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
</code></pre>
<p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p>
<blockquote>
<p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p>
</blockquote>
<h3>Option: Using a list</h3>
<p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p>
<pre><code>def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
</code></pre>
<p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p>
<h1>Question</h1>
<p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p>
<p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p>
<p>So, how do -you- return multiple values in Python?</p>
| 435 | 2008-12-10T01:55:50Z | 28,076,666 | <pre><code>>>> def func():
... return [1,2,3]
...
>>> a,b,c = func()
>>> a
1
>>> b
2
>>> c
3
</code></pre>
| 11 | 2015-01-21T20:57:30Z | [
"python",
"coding-style",
"return",
"return-value"
] |
How do you return multiple values in Python? | 354,883 | <p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p>
<h3>Option: Using a tuple</h3>
<p>Consider this trivial example:</p>
<pre><code>def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0,y1,y2)
</code></pre>
<p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p>
<h3>Option: Using a dictionary</h3>
<p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p>
<p>Consider the following:</p>
<pre><code>def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
</code></pre>
<p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p>
<p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p>
<pre><code>result['y0']
</code></pre>
<h3>Option: Using a class</h3>
<p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p>
<pre><code>class ReturnValue(object):
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code></pre>
<p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p>
<p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p>
<pre><code>class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
</code></pre>
<p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p>
<blockquote>
<p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p>
</blockquote>
<h3>Option: Using a list</h3>
<p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p>
<pre><code>def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
</code></pre>
<p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p>
<h1>Question</h1>
<p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p>
<p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p>
<p>So, how do -you- return multiple values in Python?</p>
| 435 | 2008-12-10T01:55:50Z | 36,632,980 | <p>A lot of the answers seem to suggest you need to return a collection of some sort, like a dictionary or a list. You could also leave off the extra syntax and just write out the return values, comma-separated. Note: this technically returns a tuple.</p>
<pre><code>def f():
return True, False
x, y = f()
print x
print y
</code></pre>
<p>gives:</p>
<pre><code>True
False
</code></pre>
| 9 | 2016-04-14T20:08:13Z | [
"python",
"coding-style",
"return",
"return-value"
] |
mssql handles line returns rather awkwardly | 355,135 | <p>Here is the problem: </p>
<p>for your reference:</p>
<p><img src="http://i.stack.imgur.com/mmrNH.jpg" alt="http://i.stack.imgur.com/mmrNH.jpg"></p>
<p>database entries 1,2 and 3 are made using jython 2.2.1 using jdbc1.2.
database entry 4 is made using vb the old to be replace program using odbc.</p>
<p>We have found that if I copy and paste both jython and vb MailBody entries to wordpad directly from that SQL Server Enterprise Manager software it outputs the format perfectly with correct line returns. if I compare the bytes of each file with a hex editor or KDiff3 they are binary identically the same.</p>
<p>There is a 3rd party program which consumes this data. Sadly that 3rd party program reads the data and for entries 1 to 3 it displays the data without line returns. though for entry 4 it correctly formats the text. As futher proof we can see in the picture, the data in the database is displayed differently.
Somehow the line returns are preserved in the database for the vb entries but the jython entries they are overlooked. if I click on the 'MailBody' field of entry 4 i can press down i can see the rest of the email. Whereas the data for jython is displayed in one row.</p>
<p>What gives, what am i missing, and how do I handle this?
Here is a snippet of the code where I actually send it to the database.</p>
<p>EDIT: FYI: please disregard the discrepancies in the 'Processed' column, it is irrelevant.
EDIT: what i want to do is make the jython program input the data in the same way as the vb program. So that the 3rd party program will come along and correctly display the data.
so what it will look like is every entry in 'MailBody' will display "This is a testing only!" then next line "etc etc" so if I was to do a screendump all entries would resemble database entry 4.</p>
<p><em>SOLVED</em> </p>
<p>add _force_CRLF to the mix:</p>
<pre><code>def _force_CRLF(self, data):
'''Make sure data uses CRLF for line termination.
Nicked the regex from smtplib.quotedata. '''
print data
newdata = re.sub(r'(?:\r\n|\n|\r(?!\n))', "\r\n", data)
print newdata
return newdata
def _execute_insert(self):
try:
self._stmt=self._con.prepareStatement(\
"INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\
VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))")
self._stmt.setString(1,self._emailEntryId)
self._stmt.setString(2,self._subject)
self._stmt.setString(3,self._fromWho)
self._stmt.setString(4,self._toWho)
self._stmt.setString(5,self._format_date(self._emailRecv))
self._stmt.setString(6,self._format_date(self._emailSent))
self._stmt.setString(7,str(self._attachmentCount))
self._stmt.setString(8,self._force_CRLF(self._format_email_body()))
self._stmt.execute()
self._prepare_inserting_attachment_data()
self._insert_attachment_data()
except:
raise
def _format_email_body(self):
if not self._emailBody:
return "could not extract email body"
if len(self._emailBody) > BODY_TRUNCATE_LENGTH:
return self._clean_body(self._emailBody[:BODY_TRUNCATE_LENGTH])
else:
return self._clean_body(self._emailBody)
def _clean_body(self,dirty):
'''this method simply deletes any occurrence of an '=20' that plagues my output after much testing this is not related to the line return issue, even if i comment it out I still have the problem.'''
dirty=str(dirty)
dirty=dirty.replace(r"=20","")
return r"%s"%dirty
</code></pre>
| 0 | 2008-12-10T05:10:48Z | 355,158 | <p>I suggest to add a debug output to your program, dumping character codes before insertion in DB. There are chances that Jython replace CrLf pair with single character and doesn't restore it when written to DB.</p>
| 1 | 2008-12-10T05:36:27Z | [
"java",
"python",
"sql-server",
"formatting",
"jython"
] |
mssql handles line returns rather awkwardly | 355,135 | <p>Here is the problem: </p>
<p>for your reference:</p>
<p><img src="http://i.stack.imgur.com/mmrNH.jpg" alt="http://i.stack.imgur.com/mmrNH.jpg"></p>
<p>database entries 1,2 and 3 are made using jython 2.2.1 using jdbc1.2.
database entry 4 is made using vb the old to be replace program using odbc.</p>
<p>We have found that if I copy and paste both jython and vb MailBody entries to wordpad directly from that SQL Server Enterprise Manager software it outputs the format perfectly with correct line returns. if I compare the bytes of each file with a hex editor or KDiff3 they are binary identically the same.</p>
<p>There is a 3rd party program which consumes this data. Sadly that 3rd party program reads the data and for entries 1 to 3 it displays the data without line returns. though for entry 4 it correctly formats the text. As futher proof we can see in the picture, the data in the database is displayed differently.
Somehow the line returns are preserved in the database for the vb entries but the jython entries they are overlooked. if I click on the 'MailBody' field of entry 4 i can press down i can see the rest of the email. Whereas the data for jython is displayed in one row.</p>
<p>What gives, what am i missing, and how do I handle this?
Here is a snippet of the code where I actually send it to the database.</p>
<p>EDIT: FYI: please disregard the discrepancies in the 'Processed' column, it is irrelevant.
EDIT: what i want to do is make the jython program input the data in the same way as the vb program. So that the 3rd party program will come along and correctly display the data.
so what it will look like is every entry in 'MailBody' will display "This is a testing only!" then next line "etc etc" so if I was to do a screendump all entries would resemble database entry 4.</p>
<p><em>SOLVED</em> </p>
<p>add _force_CRLF to the mix:</p>
<pre><code>def _force_CRLF(self, data):
'''Make sure data uses CRLF for line termination.
Nicked the regex from smtplib.quotedata. '''
print data
newdata = re.sub(r'(?:\r\n|\n|\r(?!\n))', "\r\n", data)
print newdata
return newdata
def _execute_insert(self):
try:
self._stmt=self._con.prepareStatement(\
"INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\
VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))")
self._stmt.setString(1,self._emailEntryId)
self._stmt.setString(2,self._subject)
self._stmt.setString(3,self._fromWho)
self._stmt.setString(4,self._toWho)
self._stmt.setString(5,self._format_date(self._emailRecv))
self._stmt.setString(6,self._format_date(self._emailSent))
self._stmt.setString(7,str(self._attachmentCount))
self._stmt.setString(8,self._force_CRLF(self._format_email_body()))
self._stmt.execute()
self._prepare_inserting_attachment_data()
self._insert_attachment_data()
except:
raise
def _format_email_body(self):
if not self._emailBody:
return "could not extract email body"
if len(self._emailBody) > BODY_TRUNCATE_LENGTH:
return self._clean_body(self._emailBody[:BODY_TRUNCATE_LENGTH])
else:
return self._clean_body(self._emailBody)
def _clean_body(self,dirty):
'''this method simply deletes any occurrence of an '=20' that plagues my output after much testing this is not related to the line return issue, even if i comment it out I still have the problem.'''
dirty=str(dirty)
dirty=dirty.replace(r"=20","")
return r"%s"%dirty
</code></pre>
| 0 | 2008-12-10T05:10:48Z | 362,847 | <p>You should look at the quopri module (and others regarding email) so you don't have to use dirty tricks as <code>_clean_body</code></p>
| 1 | 2008-12-12T14:06:49Z | [
"java",
"python",
"sql-server",
"formatting",
"jython"
] |
A get() like method for checking for Python attributes | 355,539 | <p>If I had a dictionary <code>dict</code> and I wanted to check for <code>dict['key']</code> I could either do so in a <code>try</code> block (bleh!) or use the <code>get()</code> method, with <code>False</code> as a default value.</p>
<p>I'd like to do the same thing for <code>object.attribute</code>. That is, I already have object to return <code>False</code> if it hasn't been set, but then that gives me errors like</p>
<blockquote>
<p>AttributeError: 'bool' object has no attribute 'attribute'</p>
</blockquote>
| 37 | 2008-12-10T09:49:39Z | 355,562 | <p>Do you mean <code>hasattr()</code> perhaps?</p>
<pre><code>hasattr(object, "attribute name") #Returns True or False
</code></pre>
<p><a href="http://docs.python.org/library/functions.html#hasattr" rel="nofollow">Python.org doc - Built in functions - hasattr()</a></p>
<p>You can also do this, which is a bit more cluttered and doesn't work for methods.</p>
<pre><code>"attribute" in obj.__dict__
</code></pre>
| 15 | 2008-12-10T09:59:36Z | [
"python",
"attributes"
] |
A get() like method for checking for Python attributes | 355,539 | <p>If I had a dictionary <code>dict</code> and I wanted to check for <code>dict['key']</code> I could either do so in a <code>try</code> block (bleh!) or use the <code>get()</code> method, with <code>False</code> as a default value.</p>
<p>I'd like to do the same thing for <code>object.attribute</code>. That is, I already have object to return <code>False</code> if it hasn't been set, but then that gives me errors like</p>
<blockquote>
<p>AttributeError: 'bool' object has no attribute 'attribute'</p>
</blockquote>
| 37 | 2008-12-10T09:49:39Z | 355,571 | <p>For checking if a key is in a dictionary you can use <code>in</code>: <code>'key' in dictionary</code>.</p>
<p>For checking for attributes in object use the <code>hasattr()</code> function: <code>hasattr(obj, 'attribute')</code></p>
| 5 | 2008-12-10T10:01:28Z | [
"python",
"attributes"
] |
A get() like method for checking for Python attributes | 355,539 | <p>If I had a dictionary <code>dict</code> and I wanted to check for <code>dict['key']</code> I could either do so in a <code>try</code> block (bleh!) or use the <code>get()</code> method, with <code>False</code> as a default value.</p>
<p>I'd like to do the same thing for <code>object.attribute</code>. That is, I already have object to return <code>False</code> if it hasn't been set, but then that gives me errors like</p>
<blockquote>
<p>AttributeError: 'bool' object has no attribute 'attribute'</p>
</blockquote>
| 37 | 2008-12-10T09:49:39Z | 356,227 | <p>A more direct analogue to <code>dict.get(key, default)</code> than <code>hasattr</code> is <code>getattr</code>.</p>
<pre><code>val = getattr(obj, 'attr_to_check', default_value)
</code></pre>
<p>(Where <code>default_value</code> is optional, raising an exception on no attribute if not found.)</p>
<p>For your example, you would pass <code>False</code>.</p>
| 58 | 2008-12-10T14:27:29Z | [
"python",
"attributes"
] |
Save a deque in a text file | 355,739 | <p>I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this?</p>
| 1 | 2008-12-10T11:23:19Z | 355,760 | <p>As an alternative, you could set up an exit function, and pickle the deque on exit.</p>
<p><a href="http://docs.python.org/library/sys.html#sys.exitfunc" rel="nofollow">Exit function</a><br>
<a href="http://docs.python.org/library/pickle.html" rel="nofollow">Pickle</a></p>
| 4 | 2008-12-10T11:29:20Z | [
"python",
"web-crawler"
] |
Save a deque in a text file | 355,739 | <p>I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this?</p>
| 1 | 2008-12-10T11:23:19Z | 355,764 | <p>You should be able to use <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> to serialize your lists.</p>
| 1 | 2008-12-10T11:30:32Z | [
"python",
"web-crawler"
] |
Save a deque in a text file | 355,739 | <p>I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this?</p>
| 1 | 2008-12-10T11:23:19Z | 355,788 | <p>Some things that come to my mind:</p>
<ul>
<li>leave the file handle open (don't close the file everytime you wrote something)</li>
<li>or write the file every n items and catch a close signal to write the current non-written items</li>
</ul>
| 0 | 2008-12-10T11:40:00Z | [
"python",
"web-crawler"
] |
Save a deque in a text file | 355,739 | <p>I am writing a crawler in Python, in order to make Ctrl+C not to cause my crawler to start over in next run, I need to save the processing deque in a text file (one item per line) and update it every iteration, the update operation needs to be super fast. In order not to reinvent the wheel, I am asking if there is an established module to do this?</p>
| 1 | 2008-12-10T11:23:19Z | 355,992 | <p>I am not sure if I understood the question right, I am just curious, so here are few questions and suggestions:</p>
<p>Are you planning to catch the Ctrl+C interrupt and do the deque?
What happens if the crawler crashes for some arbitrary reason like an unhandled exception or crash? You loose the queue status and start over again?
from the documentation:</p>
<blockquote>
<p>Note</p>
<p>The exit function is not called when
the program is killed by a signal,
when a Python fatal internal error is
detected, or when os._exit() is
called.</p>
</blockquote>
<p>What happens when you happen to visit the same URI again, are you maintaining a visited list or something?</p>
<p>I think you should be maintaining some kind of visit and session information / status for each URI you crawl.
You can use the visit information to decide to crawl a URI or not when you visit the same URI next time.
The other info - session information - for the last session with that URI will help in picking up only the incremental stuff and if the page is not change no need to pick it up saving some db I/O costs, duplicates, etc.</p>
<p>That way you won't have to worry about the ctrl+C or a crash. If the crawler goes down for any reason, lets say after crawling 60K posts when 40K more were left, the next time crawler fills in the queue, though the queue may be huge but the crawler can check if the it has already visited the URI or not and what was the state of the page when it was crawled - optimization - does the page requires a new pick up coz it has changed or not.</p>
<p>I hope that is of some help. </p>
| 1 | 2008-12-10T13:13:45Z | [
"python",
"web-crawler"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 356,102 | <p>Try converting the exponent to a floating number, as the default behaviour of / in Python is integer division</p>
<p>n**(1/float(3))</p>
| -1 | 2008-12-10T13:54:39Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 356,110 | <p>In older versions of Python, <code>1/3</code> is equal to 0. In Python 3.0, <code>1/3</code> is equal to 0.33333333333 (and <code>1//3</code> is equal to 0).</p>
<p>So, either change your code to use <code>1/3.0</code> or switch to Python 3.0 .</p>
| 2 | 2008-12-10T13:57:42Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 356,187 | <p><a href="http://code.google.com/p/gmpy/">Gmpy</a> is a C-coded Python extension module that wraps the GMP library to provide to Python code fast multiprecision arithmetic (integer, rational, and float), random number generation, advanced number-theoretical functions, and more.</p>
<p>Includes a <code>root</code> function:</p>
<blockquote>
<p>x.root(n): returns a 2-element tuple (y,m), such that y is the
(possibly truncated) n-th root of x; m, an ordinary Python int,
is 1 if the root is exact (x==y**n), else 0. n must be an ordinary
Python int, >=0.</p>
</blockquote>
<p>For example, 20th root:</p>
<pre><code>>>> import gmpy
>>> i0=11968003966030964356885611480383408833172346450467339251
>>> m0=gmpy.mpz(i0)
>>> m0
mpz(11968003966030964356885611480383408833172346450467339251L)
>>> m0.root(20)
(mpz(567), 0)
</code></pre>
| 14 | 2008-12-10T14:17:08Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 356,206 | <p>If it's a REALLY big number. You could use a binary search.</p>
<pre><code>def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n <= x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
</code></pre>
<p>For example:</p>
<pre><code>>>> x = 237734537465873465
>>> n = 5
>>> y = find_invpow(x,n)
>>> y
2986
>>> y**n <= x <= (y+1)**n
True
>>>
>>> x = 119680039660309643568856114803834088331723464504673392511960931441>
>>> n = 45
>>> y = find_invpow(x,n)
>>> y
227661383982863143360L
>>> y**n <= x < (y+1)**n
True
>>> find_invpow(y**n,n) == y
True
>>>
</code></pre>
| 16 | 2008-12-10T14:22:21Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 356,213 | <p>Well, if you're not particularly worried about precision, you could convert it to a sting, chop off some digits, use the exponent function, and then multiply the result by the root of how much you chopped off.</p>
<p>E.g. 32123 is about equal to 32 * 1000, the cubic root is about equak to cubic root of 32 * cubic root of 1000. The latter can be calculated by dividing the number of 0s by 3.</p>
<p>This avoids the need for the use of extension modules.</p>
| -2 | 2008-12-10T14:23:20Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 356,235 | <p>Oh, for numbers <em>that</em> big, you would use the decimal module.</p>
<p>ns: your number as a string</p>
<pre><code>ns = "11968003966030964356885611480383408833172346450467339251196093144141045683463085291115677488411620264826942334897996389485046262847265769280883237649461122479734279424416861834396522819159219215308460065265520143082728303864638821979329804885526557893649662037092457130509980883789368448042961108430809620626059287437887495827369474189818588006905358793385574832590121472680866521970802708379837148646191567765584039175249171110593159305029014037881475265618958103073425958633163441030267478942720703134493880117805010891574606323700178176718412858948243785754898788359757528163558061136758276299059029113119763557411729353915848889261125855717014320045292143759177464380434854573300054940683350937992500211758727939459249163046465047204851616590276724564411037216844005877918224201569391107769029955591465502737961776799311859881060956465198859727495735498887960494256488224613682478900505821893815926193600121890632"
from decimal import Decimal
d = Decimal(ns)
one_third = Decimal("0.3333333333333333")
print d ** one_third
</code></pre>
<p>and the answer is: 2.287391878618402702753613056E+305</p>
<p>TZ pointed out that this isn't accurate... and he's right. Here's my test.</p>
<pre><code>from decimal import Decimal
def nth_root(num_decimal, n_integer):
exponent = Decimal("1.0") / Decimal(n_integer)
return num_decimal ** exponent
def test():
ns = "11968003966030964356885611480383408833172346450467339251196093144141045683463085291115677488411620264826942334897996389485046262847265769280883237649461122479734279424416861834396522819159219215308460065265520143082728303864638821979329804885526557893649662037092457130509980883789368448042961108430809620626059287437887495827369474189818588006905358793385574832590121472680866521970802708379837148646191567765584039175249171110593159305029014037881475265618958103073425958633163441030267478942720703134493880117805010891574606323700178176718412858948243785754898788359757528163558061136758276299059029113119763557411729353915848889261125855717014320045292143759177464380434854573300054940683350937992500211758727939459249163046465047204851616590276724564411037216844005877918224201569391107769029955591465502737961776799311859881060956465198859727495735498887960494256488224613682478900505821893815926193600121890632"
nd = Decimal(ns)
cube_root = nth_root(nd, 3)
print (cube_root ** Decimal("3.0")) - nd
if __name__ == "__main__":
test()
</code></pre>
<p>It's off by about 10**891</p>
| 3 | 2008-12-10T14:29:36Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 358,026 | <p>Possibly for your curiosity:</p>
<p><a href="http://en.wikipedia.org/wiki/Hensel_Lifting" rel="nofollow">http://en.wikipedia.org/wiki/Hensel_Lifting</a></p>
<p>This could be the technique that Maple would use to actually find the nth root of large numbers.</p>
<p>Pose the fact that <code>x^n - 11968003.... = 0 mod p</code>, and go from there...</p>
| 2 | 2008-12-10T23:42:49Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 358,134 | <p>You can make it run slightly faster by avoiding the while loops in favor of setting low to 10 ** (len(str(x)) / n) and high to low * 10. Probably better is to replace the len(str(x)) with the bitwise length and using a bit shift. Based on my tests, I estimate a 5% speedup from the first and a 25% speedup from the second. If the ints are big enough, this might matter (and the speedups may vary). Don't trust my code without testing it carefully. I did some basic testing but may have missed an edge case. Also, these speedups vary with the number chosen.</p>
<p>If the actual data you're using is much bigger than what you posted here, this change may be worthwhile.</p>
<pre><code>from timeit import Timer
def find_invpow(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
high = 1
while high ** n < x:
high *= 2
low = high/2
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
def find_invpowAlt(x,n):
"""Finds the integer component of the n'th root of x,
an integer such that y ** n <= x < (y + 1) ** n.
"""
low = 10 ** (len(str(x)) / n)
high = low * 10
while low < high:
mid = (low + high) // 2
if low < mid and mid**n < x:
low = mid
elif high > mid and mid**n > x:
high = mid
else:
return mid
return mid + 1
x = 237734537465873465
n = 5
tests = 10000
print "Norm", Timer('find_invpow(x,n)', 'from __main__ import find_invpow, x,n').timeit(number=tests)
print "Alt", Timer('find_invpowAlt(x,n)', 'from __main__ import find_invpowAlt, x,n').timeit(number=tests)
</code></pre>
<p>Norm 0.626754999161</p>
<p>Alt 0.566340923309</p>
| 4 | 2008-12-11T00:44:34Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 637,321 | <p>If you are looking for something standard, fast to write with high precision. I would use decimal and adjust the precision (getcontext().prec) to at least the length of x.</p>
<h2>Code (Python 3.0)</h2>
<pre><code>from decimal import *
x = '11968003966030964356885611480383408833172346450467339251\
196093144141045683463085291115677488411620264826942334897996389\
485046262847265769280883237649461122479734279424416861834396522\
819159219215308460065265520143082728303864638821979329804885526\
557893649662037092457130509980883789368448042961108430809620626\
059287437887495827369474189818588006905358793385574832590121472\
680866521970802708379837148646191567765584039175249171110593159\
305029014037881475265618958103073425958633163441030267478942720\
703134493880117805010891574606323700178176718412858948243785754\
898788359757528163558061136758276299059029113119763557411729353\
915848889261125855717014320045292143759177464380434854573300054\
940683350937992500211758727939459249163046465047204851616590276\
724564411037216844005877918224201569391107769029955591465502737\
961776799311859881060956465198859727495735498887960494256488224\
613682478900505821893815926193600121890632'
minprec = 27
if len(x) > minprec: getcontext().prec = len(x)
else: getcontext().prec = minprec
x = Decimal(x)
power = Decimal(1)/Decimal(3)
answer = x**power
ranswer = answer.quantize(Decimal('1.'), rounding=ROUND_UP)
diff = x - ranswer**Decimal(3)
if diff == Decimal(0):
print("x is the cubic number of", ranswer)
else:
print("x has a cubic root of ", answer)
</code></pre>
<h2>Answer</h2>
<p>x is the cubic number of 22873918786185635329056863961725521583023133411
451452349318109627653540670761962215971994403670045614485973722724603798
107719978813658857014190047742680490088532895666963698551709978502745901
704433723567548799463129652706705873694274209728785041817619032774248488
2965377218610139128882473918261696612098418</p>
| 6 | 2009-03-12T04:04:59Z | [
"python",
"math",
"nth-root"
] |
How to compute the nth root of a very big integer | 356,090 | <p>I need a way to compute the nth root of a long integer in Python. </p>
<p>I tried <code>pow(m, 1.0/n)</code>, but it doesn't work:</p>
<blockquote>
<p>OverflowError: long int too large to convert to float</p>
</blockquote>
<p>Any ideas?</p>
<p>By long integer I mean REALLY long integers like:</p>
<blockquote>
<p>11968003966030964356885611480383408833172346450467339251
196093144141045683463085291115677488411620264826942334897996389
485046262847265769280883237649461122479734279424416861834396522
819159219215308460065265520143082728303864638821979329804885526
557893649662037092457130509980883789368448042961108430809620626
059287437887495827369474189818588006905358793385574832590121472
680866521970802708379837148646191567765584039175249171110593159
305029014037881475265618958103073425958633163441030267478942720
703134493880117805010891574606323700178176718412858948243785754
898788359757528163558061136758276299059029113119763557411729353
915848889261125855717014320045292143759177464380434854573300054
940683350937992500211758727939459249163046465047204851616590276
724564411037216844005877918224201569391107769029955591465502737
961776799311859881060956465198859727495735498887960494256488224
613682478900505821893815926193600121890632</p>
</blockquote>
| 17 | 2008-12-10T13:49:19Z | 37,171,151 | <p>I came up with my own answer, which takes @Mahmoud Kassem's idea, simplifies the code, and makes it more reusable:</p>
<pre><code>def cube_root(x):
return decimal.Decimal(x) ** (decimal.Decimal(1) / decimal.Decimal(3))
</code></pre>
<p>I tested it in Python 3.5.1 and Python 2.7.8, and it seemed to work fine.</p>
<p>The result will have as many digits as specified by the decimal context the function is run in, which by default is 28 decimal places. According to the documentation for the <code>power</code> function in the <code>decimal</code> module, "<a href="https://docs.python.org/3/library/decimal.html#decimal.Context.power" rel="nofollow">The result is well-defined but only âalmost always correctly-roundedâ.</a>". If you need a more accurate result, it can be done as follows:</p>
<pre><code>with decimal.localcontext() as context:
context.prec = 50
print(cube_root(42))
</code></pre>
| 0 | 2016-05-11T18:55:54Z | [
"python",
"math",
"nth-root"
] |
Python FastCGI under IIS - stdout writing problems | 356,138 | <p>I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.</p>
<p>I've tried <code>sys.stdout = os.fdopen(1, 'w')</code>, but anything written there won't get to my browser.</p>
<p>The same application works without difficulty under Apache.</p>
<p>I'm using the Microsoft-provided FastCGI extension for IIS documented here: <a href="http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/" rel="nofollow">http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/</a></p>
<p>I am using these settings in fcgiext.ini:</p>
<pre>
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
</pre>
<p>Can anyone tell what's wrong or tell me where I should look to find out?</p>
<p>All suggestions greatly appreciated...</p>
| 2 | 2008-12-10T14:04:51Z | 359,330 | <p>Forgive me if this is a dumb question, but I notice this line in your config file:</p>
<blockquote>
<p>Arguments=-u C:\app\app_wsgi.py</p>
</blockquote>
<p>Are you running a WSGI application or a FastCGI app? There <em>is</em> a difference. In WSGI, writing to stdout isn't a good idea. Your program should have an application object that can be called with an environment dict and a start_response function (for more info, see <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a>). At any rate, your application's method of returning will be to return an iterable object that contains the response body, not writing to stdout.</p>
<p>Either way, you should also consider using <a href="http://code.google.com/p/isapi-wsgi/" rel="nofollow">isapi-wsgi</a>. I've never used it myself, but I hear good things about it.</p>
| 1 | 2008-12-11T13:24:48Z | [
"python",
"iis",
"stdout",
"fastcgi"
] |
Python FastCGI under IIS - stdout writing problems | 356,138 | <p>I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.</p>
<p>I've tried <code>sys.stdout = os.fdopen(1, 'w')</code>, but anything written there won't get to my browser.</p>
<p>The same application works without difficulty under Apache.</p>
<p>I'm using the Microsoft-provided FastCGI extension for IIS documented here: <a href="http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/" rel="nofollow">http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/</a></p>
<p>I am using these settings in fcgiext.ini:</p>
<pre>
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
</pre>
<p>Can anyone tell what's wrong or tell me where I should look to find out?</p>
<p>All suggestions greatly appreciated...</p>
| 2 | 2008-12-10T14:04:51Z | 359,636 | <p>On windows, it's possible to launch a proces without a valid stdin and stdout. For example, if you execute a python script with pythonw.exe, the stdout is invdalid and if you insist on writing to it, it will block after 140 characters or something.</p>
<p>Writing to another destination than stdout looks like the safest solution.</p>
| 0 | 2008-12-11T15:01:21Z | [
"python",
"iis",
"stdout",
"fastcgi"
] |
Python FastCGI under IIS - stdout writing problems | 356,138 | <p>I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.</p>
<p>I've tried <code>sys.stdout = os.fdopen(1, 'w')</code>, but anything written there won't get to my browser.</p>
<p>The same application works without difficulty under Apache.</p>
<p>I'm using the Microsoft-provided FastCGI extension for IIS documented here: <a href="http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/" rel="nofollow">http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/</a></p>
<p>I am using these settings in fcgiext.ini:</p>
<pre>
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
</pre>
<p>Can anyone tell what's wrong or tell me where I should look to find out?</p>
<p>All suggestions greatly appreciated...</p>
| 2 | 2008-12-10T14:04:51Z | 1,328,558 | <p>Following the PEP 333 you can try to log to environ['wsgi.errors'] which is usualy the logger of the web server itself when you use fastcgi. Of course this is only available when a request is called but not during application startup.</p>
<p>You can get an example in the pylons code: <a href="http://pylonshq.com/docs/en/0.9.7/logging/#logging-to-wsgi-errors" rel="nofollow">http://pylonshq.com/docs/en/0.9.7/logging/#logging-to-wsgi-errors</a></p>
| 0 | 2009-08-25T14:14:01Z | [
"python",
"iis",
"stdout",
"fastcgi"
] |
Python FastCGI under IIS - stdout writing problems | 356,138 | <p>I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.</p>
<p>I've tried <code>sys.stdout = os.fdopen(1, 'w')</code>, but anything written there won't get to my browser.</p>
<p>The same application works without difficulty under Apache.</p>
<p>I'm using the Microsoft-provided FastCGI extension for IIS documented here: <a href="http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/" rel="nofollow">http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/</a></p>
<p>I am using these settings in fcgiext.ini:</p>
<pre>
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
</pre>
<p>Can anyone tell what's wrong or tell me where I should look to find out?</p>
<p>All suggestions greatly appreciated...</p>
| 2 | 2008-12-10T14:04:51Z | 1,500,628 | <p>Do you have to use FastCGI? If not, you may want to try a ISAPI WSGI method. I have had success using:</p>
<p><a href="http://code.google.com/p/isapi-wsgi/" rel="nofollow">http://code.google.com/p/isapi-wsgi/</a></p>
<p>and have also used PyISAPIe in the past:</p>
<p><a href="http://sourceforge.net/apps/trac/pyisapie" rel="nofollow">http://sourceforge.net/apps/trac/pyisapie</a></p>
| 1 | 2009-09-30T20:58:52Z | [
"python",
"iis",
"stdout",
"fastcgi"
] |
Python FastCGI under IIS - stdout writing problems | 356,138 | <p>I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.</p>
<p>I've tried <code>sys.stdout = os.fdopen(1, 'w')</code>, but anything written there won't get to my browser.</p>
<p>The same application works without difficulty under Apache.</p>
<p>I'm using the Microsoft-provided FastCGI extension for IIS documented here: <a href="http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/" rel="nofollow">http://learn.iis.net/page.aspx/248/configuring-fastcgi-extension-for-iis60/</a></p>
<p>I am using these settings in fcgiext.ini:</p>
<pre>
ExePath=C:\Python23\python.exe
Arguments=-u C:\app\app_wsgi.py
FlushNamedPipe=1
RequestTimeout=45
IdleTimeout=120
ActivityTimeout=30
</pre>
<p>Can anyone tell what's wrong or tell me where I should look to find out?</p>
<p>All suggestions greatly appreciated...</p>
| 2 | 2008-12-10T14:04:51Z | 5,493,892 | <p>I believe having stdout closed/invalid is in accordance to the <a href="http://www.fastcgi.com/devkit/doc/fcgi-spec.html" rel="nofollow">FastCGI spec</a>:</p>
<blockquote>
<p>The Web server leaves a single file
descriptor, FCGI_LISTENSOCK_FILENO,
open when the application begins
execution. This descriptor refers to a
listening socket created by the Web
server. </p>
<p>FCGI_LISTENSOCK_FILENO equals
STDIN_FILENO. The standard descriptors
STDOUT_FILENO and STDERR_FILENO are
closed when the application begins
execution. A reliable method for an
application to determine whether it
was invoked using CGI or FastCGI is to
call
getpeername(FCGI_LISTENSOCK_FILENO),
which returns -1 with errno set to
ENOTCONN for a FastCGI application.</p>
</blockquote>
| 1 | 2011-03-31T00:05:02Z | [
"python",
"iis",
"stdout",
"fastcgi"
] |
Minimal Python build for my application's scripting needs? | 356,452 | <p>what are your advices on building a very minimalistic version of Python(2.x) for my application's scripting needs. </p>
<p>My main motive here is to keep the foot print (both memory and disk wise) as low as possible so that my native application won't suffer from any major performance hit. Even the Python DLL size is in consideration because of the possibility of increasing boot up time of my application.</p>
<p>Can we go as low as <a href="http://www.lua.org/" rel="nofollow">Lua</a> or other lightweight solutions?</p>
| 2 | 2008-12-10T15:22:41Z | 356,579 | <p>Have you tried <a href="http://www.tinypy.org/" rel="nofollow">Tiny Python</a>?</p>
| 7 | 2008-12-10T16:00:10Z | [
"python",
"scripting",
"python-embedding"
] |
Minimal Python build for my application's scripting needs? | 356,452 | <p>what are your advices on building a very minimalistic version of Python(2.x) for my application's scripting needs. </p>
<p>My main motive here is to keep the foot print (both memory and disk wise) as low as possible so that my native application won't suffer from any major performance hit. Even the Python DLL size is in consideration because of the possibility of increasing boot up time of my application.</p>
<p>Can we go as low as <a href="http://www.lua.org/" rel="nofollow">Lua</a> or other lightweight solutions?</p>
| 2 | 2008-12-10T15:22:41Z | 2,744,197 | <p>You can use only the dll</p>
| -1 | 2010-04-30T11:39:18Z | [
"python",
"scripting",
"python-embedding"
] |
Python regex findall numbers and dots | 356,483 | <p>I'm using re.findall() to extract some version numbers from an HTML file:</p>
<pre><code>>>> import re
>>> text = "<table><td><a href=\"url\">Test0.2.1.zip</a></td><td>Test0.2.1</td></table> Test0.2.1"
>>> re.findall("Test([\.0-9]*)", text)
['0.2.1.', '0.2.1', '0.2.1']
</code></pre>
<p>but I would like to only get the ones that do not end in a dot.
The filename might not always be .zip so I can't just stick .zip in the regex.</p>
<p>I wanna end up with:</p>
<pre><code>['0.2.1', '0.2.1']
</code></pre>
<p>Can anyone suggest a better regex to use? :)</p>
| 6 | 2008-12-10T15:33:09Z | 356,494 | <pre><code>re.findall(r"Test([0-9.]*[0-9]+)", text)
</code></pre>
<p>or, a bit shorter:</p>
<pre><code>re.findall(r"Test([\d.]*\d+)", text)
</code></pre>
<p>By the way - you must not escape the dot in a character class:</p>
<pre><code>[\.0-9] // matches: 0 1 2 3 4 5 6 7 8 9 . \
[.0-9] // matches: 0 1 2 3 4 5 6 7 8 9 .
</code></pre>
| 12 | 2008-12-10T15:36:07Z | [
"python",
"regex",
"findall"
] |
How would you parse indentation (python style)? | 356,638 | <p>How would you define your parser and lexer rules to parse a language that uses indentation for defining scope.</p>
<p>I have already googled and found a clever approach for parsing it by generating INDENT and DEDENT tokens in the lexer.</p>
<p>I will go deeper on this problem and post an answer if I come to something interesting, but I would like to see other approaches to the problem.</p>
<p>EDIT:
As Charlie pointed out, <a href="http://stackoverflow.com/questions/232682/how-would-you-go-about-implementing-off-side-rule">there is already another thread very similar if not the same.</a> Should my post be deleted?</p>
| 9 | 2008-12-10T16:17:25Z | 356,838 | <p>Also you can track somewhere in lexer how many ident items are preceding first line and pass it to parser. Most interesting part would be trying to pass it to parser correctly :) If your parser uses lookahead (here I mean parser may query for variable number of tokens before it really going to match even one) then trying to pass it through one global variable seems to be very bad idea (because lexer can slip on next line and change value of indent counter while parser is still trying to parse previous line). Also globals are evil in many other cases ;) Marking first line 'real' token in someway with indent counter is more reasonable. I can't give you exact example (I don't even know what parser and lexer generators are you going to use if any...) but something like storing data on first line tokens (it could be non comfortable if you can't easily get such token from parser) or saving custom data (map that links tokens to indent, array where every line in source code as index and indent value as element value) seems to be enough. One downside of this approach is additional complexity to parser that will need to distinguish between ident values and change its behavior based on it. Something like LOOKAHEAD({ yourConditionInJava }) for JavaCC may work here but it is <strong>NOT</strong> a very good idea. A lot of additional tokens in your approach seems to be less evil thing to use :)</p>
<p>As another alternative I would suggest is to mix this two approaches. You could generate additional tokens only when indent counter changes its value on next line. It is like artificial BEGIN and END token. In this way you may lower number of 'artificial' tokens in your stream fed into parser from lexer. Only your parser grammar should be adjusted to understand additional tokens...</p>
<p>I didn't tried this (have no real experience with such languages parsing), just sharing my thoughts about possible solutions. Checking already built parsers for this kinds of languages could be of great value for you. Open source is your friend ;)</p>
| 1 | 2008-12-10T17:18:57Z | [
"python",
"parsing",
"indentation",
"lexer"
] |
How would you parse indentation (python style)? | 356,638 | <p>How would you define your parser and lexer rules to parse a language that uses indentation for defining scope.</p>
<p>I have already googled and found a clever approach for parsing it by generating INDENT and DEDENT tokens in the lexer.</p>
<p>I will go deeper on this problem and post an answer if I come to something interesting, but I would like to see other approaches to the problem.</p>
<p>EDIT:
As Charlie pointed out, <a href="http://stackoverflow.com/questions/232682/how-would-you-go-about-implementing-off-side-rule">there is already another thread very similar if not the same.</a> Should my post be deleted?</p>
| 9 | 2008-12-10T16:17:25Z | 356,954 | <p>This is kind of hypothetical, as it would depend on what technology you have for your lexer and parser, but the easiest way would seem to be to have BEGINBLOCK and ENDBLOCK tokens analogous to braces in C. Using the <a href="http://en.wikipedia.org/wiki/Off-side_rule">"offsides rule"</a> your lexer needs to keep track of a stack of indendtation levels. When the indent level increases, emit a BEGINBLOCK for the parser; when the indentation level decreases, emit ENDBLOCK and pop levels off the stack.</p>
<p><a href="http://stackoverflow.com/questions/232682/how-would-you-go-about-implementing-off-side-rule">Here's another discussion</a> of this on SO, btw.</p>
| 10 | 2008-12-10T17:48:55Z | [
"python",
"parsing",
"indentation",
"lexer"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 356,782 | <p>You can check the type of the argument passed to your constructor inside:</p>
<pre><code>def __init__(self, r = 0, g = 0, b = 0):
# if r is a list
if (type(r) == type([1,2,3])):
r, g, b = r[0], r[1], r[2]
# if r is a color
if (type(r) == type(self)):
r, g, b = r.r, r.g, r.b
self.r = r
self.g = g
self.b = b
</code></pre>
<p>Maybe that will help.</p>
| -1 | 2008-12-10T17:05:22Z | [
"python"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 356,820 | <p>You can have the factory methods, it is fine. But why not just call it as it is?</p>
<pre><code>Color(r, g, b)
Color(*[r, g, b])
Color(**{'r': r, 'g': g, 'b': b})
</code></pre>
<p>This is the python way. As for the from object constructor, I would prefer something like:</p>
<pre><code>Color(*Color2.as_list())
</code></pre>
<p><em>Explicit is better than implicit</em> - Python Zen</p>
| 10 | 2008-12-10T17:14:02Z | [
"python"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 357,004 | <p>Python doesn't accept multiple methods with the same name, period. One method does one thing.</p>
<p>I've seen different approaches recommended on how to handle this ... classmethods (like you outlined above) or factory functions. I like keyword arguments the most.</p>
<pre><code>class Color (object):
def __init__(self, **parms):
if parms.get('list'):
self.r, self.g, self.b = parms['list']
elif parms.get('color'):
color = parms['color']
self.r = color.r
self.g = color.g
self.b = color.b
else:
self.r = parms['red']
self.g = parms['green']
self.b = parms['blue']
c1 = Color(red=220, green=0, blue=270)
c2 = Color(list=[220, 0, 70])
c3 = Color(color=c1)
</code></pre>
<p>This fits the Python way of being explicit and readable, plus it easily allows you to add new arguments if needed. </p>
<p>EDIT: Plus I don't have to look at the actual constructor code to understand the arguments. The explanation is supplied by the keyword.</p>
| 7 | 2008-12-10T18:02:06Z | [
"python"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 357,006 | <p>Python always fully replaces methods with the same name. Unlike C# that, if I remember correctly, will make the methods with the same name options for different argument input.</p>
<p>If there's only a variation of one in the keywords, like either 3 or 4 arguments of the same type, I'd say using a preset of the last argument, or all of them, would be the way to go.</p>
<p>However, if you want lists, tuples and other types, you should probably go for the arbitrary arguments list and test the contents of that in the function</p>
<pre><code>def function(*args):
if type(args[0]) is int:
dothis()
#and so on
</code></pre>
| 0 | 2008-12-10T18:02:28Z | [
"python"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 357,256 | <p>In general, use factory methods, marked up as <code>@classmethod</code>s. They'll also work correctly on subclasses. From a design perspective, they are more explicit, especially when given a good name. </p>
<p>In this case, mixing everything together is probably more convenient, but it also makes the contract for your constructor more difficult.</p>
| 9 | 2008-12-10T19:22:09Z | [
"python"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 357,288 | <p>On the <code>__add__</code> issue:</p>
<p>First, you cannot get "three integers", I assume you mean a 3-tuple of integers?</p>
<p>In that case, you won't get around some <code>isinstance</code> calls:</p>
<pre><code>def __add__(self, other):
if isinstance(other, Color):
...
elif isinstance(other, (int, long)):
...
elif len(other) == 3 and all(isinstance(e, (int, long)) for e in other):
...
else:
raise TypeError("Can only add Color to Color, int or three-tuple")
</code></pre>
<p>You might also want to add implementations of <code>__radd__</code>, so that you can handle</p>
<pre><code>1 + Color(1, 2, 3)
</code></pre>
<p>but that's just</p>
<pre><code>def __radd__(self, other):
return self.__add__(other)
</code></pre>
<p>although strictly, it will never be called when <code>type(other) is Color</code>. </p>
<p>Also, do not forget <code>__iadd__</code> to support <code>+=</code>.</p>
| 2 | 2008-12-10T19:30:23Z | [
"python"
] |
How to handle constructors or methods with a different set (or type) of arguments in Python? | 356,718 | <p>Is there a way in Python, to have more than one constructor or more than one method with the <em>same name</em>, who differ in the <em>number of arguments</em> they accept or the <em>type(s) of one or more argument(s)</em>?</p>
<p>If not, what would be the best way to handle such situations?</p>
<p>For an example I made up a color class. <em>This class should only work as a basic example to discuss this</em>, there is lot's of unnecessary and/or redundant stuff in there.</p>
<p>It would be nice, if I could call the constructor with different objects (a list, an other color object or three integers...) and the constructor handles them accordingly. In this basic example it works in some cases with * args and * * kwargs, but using class methods is the only general way I came up with. What would be a "<strong>best practice</strong>" like solution for this?</p>
<p>The constructor aside, if I would like to implement an _ _ <strong>add</strong> _ _ method too, how can I get this method to accept all of this: A plain integer (which is added to all values), three integers (where the first is added to the red value and so forth) or another color object (where both red values are added together, etc.)?</p>
<p><strong>EDIT</strong></p>
<ul>
<li><p>I added an <em>alternative</em> constructor (initializer, _ _ <strong>init</strong> _ _) that basicly does all the stuff I wanted.</p></li>
<li><p>But I stick with the first one and the factory methods. Seems clearer.</p></li>
<li><p>I also added an _ _ <strong>add</strong> _ _, which does all the things mentioned above but I'm not sure if it's <em>good style</em>. I try to use the iteration protocol and fall back to "single value mode" instead of checking for specific types. Maybe still ugly tho.</p></li>
<li><p>I have taken a look at _ _ <strong>new</strong> _ _, thanks for the links.</p></li>
<li><p>My first quick try with it fails: I filter the rgb values from the * args and * * kwargs (is it a class, a list, etc.) then call the superclass's _ _ new _ _ with the right args (just r,g,b) to pass it along to init. The call to the 'Super(cls, self)._ _ new _ _ (....)' works, but since I generate and return the same object as the one I call from (as intended), all the original args get passed to _ _ init _ _ (working as intended), so it bails. </p></li>
<li><p>I could get rid of the _ _ init _ _ completly and set the values in the _ _ new _ _ but I don't know... feels like I'm abusing stuff here ;-) I should take a good look at metaclasses and new first I guess.</p></li>
</ul>
<p>Source:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Color (object):
# It's strict on what to accept, but I kinda like it that way.
def __init__(self, r=0, g=0, b=0):
self.r = r
self.g = g
self.b = b
# Maybe this would be a better __init__?
# The first may be more clear but this could handle way more cases...
# I like the first more though. What do you think?
#
#def __init__(self, obj):
# self.r, self.g, self.b = list(obj)[:3]
# This methods allows to use lists longer than 3 items (eg. rgba), where
# 'Color(*alist)' would bail
@classmethod
def from_List(cls, alist):
r, g, b = alist[:3]
return cls(r, g, b)
# So we could use dicts with more keys than rgb keys, where
# 'Color(**adict)' would bail
@classmethod
def from_Dict(cls, adict):
return cls(adict['r'], adict['g'], adict['b'])
# This should theoreticaly work with every object that's iterable.
# Maybe that's more intuitive duck typing than to rely on an object
# to have an as_List() methode or similar.
@classmethod
def from_Object(cls, obj):
return cls.from_List(list(obj))
def __str__(self):
return "<Color(%s, %s, %s)>" % (self.r, self.g, self.b)
def _set_rgb(self, r, g, b):
self.r = r
self.g = g
self.b = b
def _get_rgb(self):
return (self.r, self.g, self.b)
rgb = property(_get_rgb, _set_rgb)
def as_List(self):
return [self.r, self.g, self.b]
def __iter__(self):
return (c for c in (self.r, self.g, self.b))
# We could add a single value (to all colorvalues) or a list of three
# (or more) values (from any object supporting the iterator protocoll)
# one for each colorvalue
def __add__(self, obj):
r, g, b = self.r, self.g, self.b
try:
ra, ga, ba = list(obj)[:3]
except TypeError:
ra = ga = ba = obj
r += ra
g += ga
b += ba
return Color(*Color.check_rgb(r, g, b))
@staticmethod
def check_rgb(*vals):
ret = []
for c in vals:
c = int(c)
c = min(c, 255)
c = max(c, 0)
ret.append(c)
return ret
class ColorAlpha(Color):
def __init__(self, r=0, g=0, b=0, alpha=255):
Color.__init__(self, r, g, b)
self.alpha = alpha
def __str__(self):
return "<Color(%s, %s, %s, %s)>" % (self.r, self.g, self.b, self.alpha)
# ...
if __name__ == '__main__':
l = (220, 0, 70)
la = (57, 58, 61, 255)
d = {'r': 220, 'g': 0, 'b':70}
da = {'r': 57, 'g': 58, 'b':61, 'a':255}
c = Color(); print c # <Color(0, 0, 0)>
ca = ColorAlpha(*la); print ca # <Color(57, 58, 61, 255)>
print '---'
c = Color(220, 0, 70); print c # <Color(220, 0, 70)>
c = Color(*l); print c # <Color(220, 0, 70)>
#c = Color(*la); print c # -> Fail
c = Color(**d); print c # <Color(220, 0, 70)>
#c = Color(**da); print c # -> Fail
print '---'
c = Color.from_Object(c); print c # <Color(220, 0, 70)>
c = Color.from_Object(ca); print c # <Color(57, 58, 61, 255)>
c = Color.from_List(l); print c # <Color(220, 0, 70)>
c = Color.from_List(la); print c # <Color(57, 58, 61, 255)>
c = Color.from_Dict(d); print c # <Color(220, 0, 70)>
c = Color.from_Dict(da); print c # <Color(57, 58, 61, 255)>
print '---'
print 'Check =', Color.check_rgb('1', 0x29a, -23, 40)
# Check = [1, 255, 0, 40]
print '%s + %s = %s' % (c, 10, c + 10)
# <Color(57, 58, 61)> + 10 = <Color(67, 68, 71)>
print '%s + %s = %s' % (c, ca, c + ca)
# <Color(57, 58, 61)> + <Color(57, 58, 61, 255)> = <Color(114, 116, 122)>
</code></pre>
| 14 | 2008-12-10T16:42:08Z | 7,781,667 | <p>My first advise is to use factory methods.</p>
<p>Although if you really want a single method, give it something to dispatch on for
handling the parameters. </p>
<pre><code>def __init__(self, method, *args, **kw):
getattr(self, '_init_'+method)(*args, **kw)
def _init_coponents(self, r, g, b):
...
def _init_fromColor(self, color):
...
</code></pre>
<p>And use like:</p>
<pre><code>c1 = Color('components', 0, 0, 0,)
c2 = Color('fromColor', c1)
</code></pre>
<p>While this adds another parameter, it is still way better than type tests and keeps stuff explicit. It provides nice exceptions out of the box on illegal calls, and is easily extendable even in subclasses.</p>
| 1 | 2011-10-16T00:54:16Z | [
"python"
] |
Pexpect, running ssh-copy-id is hanging when trying to spawn a second process | 356,830 | <p>I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.</p>
<p>I have basically this:</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>and then I want to spawn another process, I don't care about this one anymore, whether it ended or not.</p>
<pre><code>child = pexpect.spawn('command2')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>And the code is hanging at the second "spawn"</p>
<p>However, if I comment out the first call, the second one works, so i'm guessing that the fact that the first one is still running or something is keeping it from working.</p>
<p>Now, the other thing I haven't been able to do is wait until the first one stops.
I've tried:<br />
child.close() - it hangs (both with True and False as parameters)
child.read(-1) - it hangs<br />
child.expect(pexpect.EOF) - it hangs.<br />
child.terminate() - it hangs (both with True and False as parameters)</p>
<p>Any ideas on what could be happening?<br />
NOTE: I'm not a Python expert, and i have never used pexpect before, so ANY idea is more than welcome.</p>
<p>Thanks!</p>
<p><hr /></p>
<p>UPDATE: This is definitely related to ssh-copy-id, because with other processes, spawn works well even if they don't return.
Also, apparently ssh-copy-id never returns an EOF.</p>
| 6 | 2008-12-10T17:16:31Z | 357,021 | <p>Reading <a href="http://pexpect.sourceforge.net/pexpect.html#spawn" rel="nofollow">pexpect documentation for spawn</a>, I think it is waiting for the command to terminate.</p>
<p>I would suggest a couple of different possibilities, depending on your needs:</p>
<p>1) Kill the spawned process. However, this may lead to corruption in your operation, so I do not know if it is what you want.</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
child.close(True)
</code></pre>
<p>2) Wait for completion of the initial task before moving to the next one</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
child.wait()
child = pexpect.spawn('command2')
...
</code></pre>
<p>3) Use a different instance for all children, then wait on all of them at the end - and this would be most probably the best solution</p>
<pre><code>def exec_command(cmd):
child = pexpect.spawn(cmd)
child.expect('password:')
child.sendline('the password')
return child
commands = ['command1', 'command2']
childrens = [exec_command(cmd) for cmd in commands]
for child in childrens:
child.wait()
</code></pre>
<p>Note: all of the code here is untested, and written under the assumption that your script is hanging because deleting a spawn object will hang until the command will terminate.</p>
| 0 | 2008-12-10T18:10:05Z | [
"python",
"process",
"pexpect"
] |
Pexpect, running ssh-copy-id is hanging when trying to spawn a second process | 356,830 | <p>I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.</p>
<p>I have basically this:</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>and then I want to spawn another process, I don't care about this one anymore, whether it ended or not.</p>
<pre><code>child = pexpect.spawn('command2')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>And the code is hanging at the second "spawn"</p>
<p>However, if I comment out the first call, the second one works, so i'm guessing that the fact that the first one is still running or something is keeping it from working.</p>
<p>Now, the other thing I haven't been able to do is wait until the first one stops.
I've tried:<br />
child.close() - it hangs (both with True and False as parameters)
child.read(-1) - it hangs<br />
child.expect(pexpect.EOF) - it hangs.<br />
child.terminate() - it hangs (both with True and False as parameters)</p>
<p>Any ideas on what could be happening?<br />
NOTE: I'm not a Python expert, and i have never used pexpect before, so ANY idea is more than welcome.</p>
<p>Thanks!</p>
<p><hr /></p>
<p>UPDATE: This is definitely related to ssh-copy-id, because with other processes, spawn works well even if they don't return.
Also, apparently ssh-copy-id never returns an EOF.</p>
| 6 | 2008-12-10T17:16:31Z | 357,107 | <p>Actually, I tried many of these alternatives, and neither worked. </p>
<ul>
<li>Calling close() or terminate() hangs (both with True and False as parameters)</li>
<li>Calling wait() or read(-1) or expect(pexpect.EOF) hangs</li>
<li>calling spawn again without caring about the previous spawn command hangs</li>
</ul>
<p>I made some tests with other commands (like 'ftp', and they work as i'd expect, for example, if you call .expect('something'), and something is not found before EOF, they don't wait forever, they throw an exception, so I believe this is related to the ssh-copy-id command specifically.</p>
| 0 | 2008-12-10T18:43:21Z | [
"python",
"process",
"pexpect"
] |
Pexpect, running ssh-copy-id is hanging when trying to spawn a second process | 356,830 | <p>I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.</p>
<p>I have basically this:</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>and then I want to spawn another process, I don't care about this one anymore, whether it ended or not.</p>
<pre><code>child = pexpect.spawn('command2')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>And the code is hanging at the second "spawn"</p>
<p>However, if I comment out the first call, the second one works, so i'm guessing that the fact that the first one is still running or something is keeping it from working.</p>
<p>Now, the other thing I haven't been able to do is wait until the first one stops.
I've tried:<br />
child.close() - it hangs (both with True and False as parameters)
child.read(-1) - it hangs<br />
child.expect(pexpect.EOF) - it hangs.<br />
child.terminate() - it hangs (both with True and False as parameters)</p>
<p>Any ideas on what could be happening?<br />
NOTE: I'm not a Python expert, and i have never used pexpect before, so ANY idea is more than welcome.</p>
<p>Thanks!</p>
<p><hr /></p>
<p>UPDATE: This is definitely related to ssh-copy-id, because with other processes, spawn works well even if they don't return.
Also, apparently ssh-copy-id never returns an EOF.</p>
| 6 | 2008-12-10T17:16:31Z | 357,749 | <p>I think the problem is, that SSH tries to open PTY and it does not work
on anything else than PTY for security reasons. This won't work well
with pexpect.</p>
<p>I have another ssh client:</p>
<p><a href="http://www.digmia.com/index.php?option=com_content&view=article&id=54:Digmia%20Enterprise%20SSH&Itemid=56" rel="nofollow">http://www.digmia.com/index.php?option=com_content&view=article&id=54:Digmia%20Enterprise%20SSH&Itemid=56</a></p>
<p>It's open-source, you can use it. What you are trying to do would
be more commands, but you don't need expect at all.</p>
<ol>
<li><p>First install it accordingly to manual, then do something like this:</p></li>
<li><p>Run dssh-agent, add the password you need like this:</p>
<pre><code>dssh-add -l < passwordfile
</code></pre>
<ul>
<li><p>or if it is a secure machine, i.e. no one else can log in there,
this is <em>very</em> important, otherwise this would be a huge security hole:</p>
<pre><code>echo "name-of-server;22;root;password;" | dssh-add -l
</code></pre></li>
<li><p><code>password</code> file would be something like:</p>
<pre><code>name-of-server;22;root;password;
</code></pre></li>
</ul></li>
<li><p>And the do something like (replace <code>CONTENTS OF ...</code> with actual content of that file):</p>
<pre><code>dssh root@name-of-server -- echo "CONTENTS OF ~/.ssh/identity.pub" > .ssh/authorized_keys \; chmod og-w .ssh .ssh/authorized_keys
</code></pre>
<ul>
<li><p>You can (optionally) do</p>
<pre><code>dssh-add -f passwords
</code></pre></li>
</ul>
<p>(make sure no one else is doing all this stuff, otherwise you would
have a race condition).</p></li>
</ol>
<p>Also, pexpect should probably work with dssh itself (so you don't need
to use dssh-agent). But using dssh-agent is simpler and safer.</p>
<p>Installation manual for DSSH is contained in the tarball.</p>
<p>I don't know any simpler way of doing this, OpenSSH ssh-copy-id is
very picky about where the password comes from...</p>
| 1 | 2008-12-10T21:53:02Z | [
"python",
"process",
"pexpect"
] |
Pexpect, running ssh-copy-id is hanging when trying to spawn a second process | 356,830 | <p>I'm doing a Python script where I need to spawn several ssh-copy-id processes, and they need for me to type in a password, so i'm using PExpect.</p>
<p>I have basically this:</p>
<pre><code>child = pexpect.spawn('command')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>and then I want to spawn another process, I don't care about this one anymore, whether it ended or not.</p>
<pre><code>child = pexpect.spawn('command2')
child.expect('password:')
child.sendline('the password')
</code></pre>
<p>And the code is hanging at the second "spawn"</p>
<p>However, if I comment out the first call, the second one works, so i'm guessing that the fact that the first one is still running or something is keeping it from working.</p>
<p>Now, the other thing I haven't been able to do is wait until the first one stops.
I've tried:<br />
child.close() - it hangs (both with True and False as parameters)
child.read(-1) - it hangs<br />
child.expect(pexpect.EOF) - it hangs.<br />
child.terminate() - it hangs (both with True and False as parameters)</p>
<p>Any ideas on what could be happening?<br />
NOTE: I'm not a Python expert, and i have never used pexpect before, so ANY idea is more than welcome.</p>
<p>Thanks!</p>
<p><hr /></p>
<p>UPDATE: This is definitely related to ssh-copy-id, because with other processes, spawn works well even if they don't return.
Also, apparently ssh-copy-id never returns an EOF.</p>
| 6 | 2008-12-10T17:16:31Z | 1,662,962 | <p>Fortunately or not, but OpenSSH client seems to be very picky about passwords and where they come from.</p>
<p>You may try using <a href="http://www.lag.net/paramiko/" rel="nofollow">Paramiko</a> Python SSH2 library. Here's a simple <a href="http://www.lag.net/pipermail/paramiko/2006-January/000180.html" rel="nofollow">example how to use it with password authentication</a>, then issue some shell commands (<code>echo "..." >> $HOME/.ssh/authorized_keys</code> being the simplest) to add your public key on remote host.</p>
| 3 | 2009-11-02T18:49:35Z | [
"python",
"process",
"pexpect"
] |
Proper way of cancelling accept and closing a Python processing/multiprocessing Listener connection | 357,656 | <p>(I'm using the <a href="http://developer.berlios.de/projects/pyprocessing" rel="nofollow">pyprocessing</a> module in this example, but replacing processing with multiprocessing should probably work if you run <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">python 2.6</a> or use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">multiprocessing backport</a>)</p>
<p>I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:</p>
<pre><code>import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno
# This is actually called by the connection handler.
def closeme():
time.sleep(1)
print 'Closing socket...'
listener.close()
os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)
oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)
listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
listener.accept()
except socket.error, e:
if e.args[0] != errno.EINTR:
raise
# Cleanup here...
print 'Done...'
</code></pre>
<p>The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.</p>
<p>Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.</p>
<p><strong>Clarification</strong>:
Thanks all! As usual, ambiguities in my original question are revealed :)</p>
<ul>
<li>I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.</li>
<li>I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy</li>
<li>The reasons for threads are that:
<ul>
<li>They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.</li>
<li>I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.</li>
</ul></li>
</ul>
<p>Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.</p>
| 10 | 2008-12-10T21:25:18Z | 357,793 | <p>Probably not ideal, but you can release the block by sending the socket some data from the signal handler or the thread that is terminating the process.</p>
<p>EDIT: Another way to implement this might be to use the <strike>Connection</strike> <a href="http://docs.python.org/dev/library/multiprocessing.html#pipes-and-queues" rel="nofollow">Queues</a>, since they seem to support timeouts (apologies, I misread your code in my first read).</p>
| 0 | 2008-12-10T22:14:28Z | [
"python",
"sockets",
"multiprocessing"
] |
Proper way of cancelling accept and closing a Python processing/multiprocessing Listener connection | 357,656 | <p>(I'm using the <a href="http://developer.berlios.de/projects/pyprocessing" rel="nofollow">pyprocessing</a> module in this example, but replacing processing with multiprocessing should probably work if you run <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">python 2.6</a> or use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">multiprocessing backport</a>)</p>
<p>I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:</p>
<pre><code>import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno
# This is actually called by the connection handler.
def closeme():
time.sleep(1)
print 'Closing socket...'
listener.close()
os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)
oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)
listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
listener.accept()
except socket.error, e:
if e.args[0] != errno.EINTR:
raise
# Cleanup here...
print 'Done...'
</code></pre>
<p>The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.</p>
<p>Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.</p>
<p><strong>Clarification</strong>:
Thanks all! As usual, ambiguities in my original question are revealed :)</p>
<ul>
<li>I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.</li>
<li>I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy</li>
<li>The reasons for threads are that:
<ul>
<li>They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.</li>
<li>I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.</li>
</ul></li>
</ul>
<p>Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.</p>
| 10 | 2008-12-10T21:25:18Z | 358,392 | <p>I'm new to the multiprocessing module, but it seems to me that mixing the processing module and the threading module is counter-intuitive, aren't they targetted at solving the same problem?</p>
<p>Anyway, how about wrapping your listen functions into a process itself? I'm not clear how this affects the rest of your code, but this may be a cleaner alternative.</p>
<pre><code>from multiprocessing import Process
from multiprocessing.connection import Listener
class ListenForConn(Process):
def run(self):
listener = Listener('/tmp/asdf', 'AF_UNIX')
listener.accept()
# do your other handling here
listen_process = ListenForConn()
listen_process.start()
print listen_process.is_alive()
listen_process.terminate()
listen_process.join()
print listen_process.is_alive()
print 'No more listen process.'
</code></pre>
| 1 | 2008-12-11T03:46:03Z | [
"python",
"sockets",
"multiprocessing"
] |
Proper way of cancelling accept and closing a Python processing/multiprocessing Listener connection | 357,656 | <p>(I'm using the <a href="http://developer.berlios.de/projects/pyprocessing" rel="nofollow">pyprocessing</a> module in this example, but replacing processing with multiprocessing should probably work if you run <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">python 2.6</a> or use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">multiprocessing backport</a>)</p>
<p>I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:</p>
<pre><code>import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno
# This is actually called by the connection handler.
def closeme():
time.sleep(1)
print 'Closing socket...'
listener.close()
os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)
oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)
listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
listener.accept()
except socket.error, e:
if e.args[0] != errno.EINTR:
raise
# Cleanup here...
print 'Done...'
</code></pre>
<p>The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.</p>
<p>Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.</p>
<p><strong>Clarification</strong>:
Thanks all! As usual, ambiguities in my original question are revealed :)</p>
<ul>
<li>I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.</li>
<li>I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy</li>
<li>The reasons for threads are that:
<ul>
<li>They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.</li>
<li>I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.</li>
</ul></li>
</ul>
<p>Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.</p>
| 10 | 2008-12-10T21:25:18Z | 431,549 | <p>Isnt that what select is for??</p>
<p>Only call accept on the socket if the select indicates it will not block...</p>
<p>The select has a timeout, so you can break out occasionally occasionally to check
if its time to shut down....</p>
| 3 | 2009-01-10T19:03:29Z | [
"python",
"sockets",
"multiprocessing"
] |
Proper way of cancelling accept and closing a Python processing/multiprocessing Listener connection | 357,656 | <p>(I'm using the <a href="http://developer.berlios.de/projects/pyprocessing" rel="nofollow">pyprocessing</a> module in this example, but replacing processing with multiprocessing should probably work if you run <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">python 2.6</a> or use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">multiprocessing backport</a>)</p>
<p>I currently have a program that listens to a unix socket (using a processing.connection.Listener), accept connections and spawns a thread handling the request. At a certain point I want to quit the process gracefully, but since the accept()-call is blocking and I see no way of cancelling it in a nice way. I have one way that works here (OS X) at least, setting a signal handler and signalling the process from another thread like so:</p>
<pre><code>import processing
from processing.connection import Listener
import threading
import time
import os
import signal
import socket
import errno
# This is actually called by the connection handler.
def closeme():
time.sleep(1)
print 'Closing socket...'
listener.close()
os.kill(processing.currentProcess().getPid(), signal.SIGPIPE)
oldsig = signal.signal(signal.SIGPIPE, lambda s, f: None)
listener = Listener('/tmp/asdf', 'AF_UNIX')
# This is a thread that handles one already accepted connection, left out for brevity
threading.Thread(target=closeme).start()
print 'Accepting...'
try:
listener.accept()
except socket.error, e:
if e.args[0] != errno.EINTR:
raise
# Cleanup here...
print 'Done...'
</code></pre>
<p>The only other way I've thought about is reaching deep into the connection (listener._listener._socket) and setting the non-blocking option...but that probably has some side effects and is generally really scary.</p>
<p>Does anyone have a more elegant (and perhaps even correct!) way of accomplishing this? It needs to be portable to OS X, Linux and BSD, but Windows portability etc is not necessary.</p>
<p><strong>Clarification</strong>:
Thanks all! As usual, ambiguities in my original question are revealed :)</p>
<ul>
<li>I need to perform cleanup after I have cancelled the listening, and I don't always want to actually exit that process.</li>
<li>I need to be able to access this process from other processes not spawned from the same parent, which makes Queues unwieldy</li>
<li>The reasons for threads are that:
<ul>
<li>They access a shared state. Actually more or less a common in-memory database, so I suppose it could be done differently.</li>
<li>I must be able to have several connections accepted at the same time, but the actual threads are blocking for something most of the time. Each accepted connection spawns a new thread; this in order to not block all clients on I/O ops.</li>
</ul></li>
</ul>
<p>Regarding threads vs. processes, I use threads for making my blocking ops non-blocking and processes to enable multiprocessing.</p>
| 10 | 2008-12-10T21:25:18Z | 465,361 | <p>I thought I could avoid it, but it seems I have to do something like this:</p>
<pre><code>from processing import connection
connection.Listener.fileno = lambda self: self._listener._socket.fileno()
import select
l = connection.Listener('/tmp/x', 'AF_UNIX')
r, w, e = select.select((l, ), (), ())
if l in r:
print "Accepting..."
c = l.accept()
# ...
</code></pre>
<p>I am aware that this breaks the law of demeter and introduces some evil monkey-patching, but it seems this would be the most easy-to-port way of accomplishing this. If anyone has a more elegant solution I would be happy to hear it :)</p>
| 1 | 2009-01-21T13:46:04Z | [
"python",
"sockets",
"multiprocessing"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 357,826 | <p>Python is well suited for folding on indent, bit for writing my own code I use markers as they can crunch a document down the way you want it and can serve as a kind of a table of contents. I have this in my vimrc to flip between the two when I'm viewing someone elses code. </p>
<pre><code>#Toggle fold methods \fo
let g:FoldMethod = 0
map <leader>fo :call ToggleFold()<cr>
fun! ToggleFold()
if g:FoldMethod == 0
exe 'set foldmethod=indent'
let g:FoldMethod = 1
else
exe 'set foldmethod=marker'
let g:FoldMethod = 0
endif
endfun
#Add markers (trigger on class Foo line)
nnoremap ,f2 ^wywO#<c-r>0 {{{2<esc>
nnoremap ,f3 ^wywO#<c-r>0 {{{3<esc>
nnoremap ,f4 ^wywO#<c-r>0 {{{4<esc>
nnoremap ,f1 ^wywO#<c-r>0 {{{1<esc>
</code></pre>
| 5 | 2008-12-10T22:26:19Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 357,833 | <p>I really like the <a href="http://www.vim.org/scripts/script.php?script_id=2002" rel="nofollow"><code>python_ifold</code> plugin</a>.</p>
| 5 | 2008-12-10T22:29:04Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 358,619 | <p>Try this plugin:</p>
<p><a href="http://vim.sourceforge.net/scripts/script.php?script_id=515" rel="nofollow">http://vim.sourceforge.net/scripts/script.php?script_id=515</a></p>
| 4 | 2008-12-11T07:23:05Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 360,634 | <p>Personally I can't convince myself to litter my code with the markers. I've become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I'm right at home. Perfect for Python!</p>
<blockquote>
<p><code>nnoremap <space> za</code></p>
<p><code>vnoremap <space> zf</code></p>
</blockquote>
| 83 | 2008-12-11T19:47:43Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 361,548 | <p>I use <a href="http://www.vim.org/scripts/script.php?script_id=2462" title="this">this</a> syntax file for Python. It sets the folding method to syntax and folds all classes and functions, but nothing else.</p>
| 21 | 2008-12-12T00:32:01Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 418,603 | <p>The Python source comes with a vim syntax plugin along with a custom vimrc file. Check the <a href="http://web.archive.org/web/20101128033925/http://python.org/dev/faq/" rel="nofollow">python FAQ on vim</a></p>
| 3 | 2009-01-06T23:24:48Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 1,868,951 | <p>I think that indent folding is fine for python. I'm making a multi-branched git repo for vim-config python/django IDE ideas. Fork away!</p>
<p><a href="http://github.com/skyl/vim-config-python-ide">http://github.com/skyl/vim-config-python-ide</a></p>
| 5 | 2009-12-08T18:32:36Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 21,112,061 | <p>For me the ideal folding is to fold just the <code>class</code> and <code>def</code> blocks, indent folding is too much for my taste. I think one elegant solution is to use the syntax system like this <a href="http://www.vim.org/scripts/script.php?script_id=2462" rel="nofollow">one</a> mentioned by Tomas. However, this one is meant to replace the original syntax file and it may end being older than the original (i.e. that script doesn't mention Python 3 syntax). </p>
<p>My solution is to place in the <code>~/.vim/syntax</code> folder a file named <code>python.vim</code> with just the important lines (taken from the above script):</p>
<pre><code>syn match pythonDefStatement /^\s*\%(def\|class\)/
\ nextgroup=pythonFunction skipwhite
syn region pythonFunctionFold start="^\z(\s*\)\%(def\|class\)\>"
\ end="\ze\%(\s*\n\)\+\%(\z1\s\)\@!." fold transparent
hi link pythonDefStatement Statement
</code></pre>
<p>Then simply activate the folding with <code>:set foldmethod=syntax</code>.</p>
| 2 | 2014-01-14T11:09:43Z | [
"python",
"vim",
"folding"
] |
What is the recommended way to use Vim folding for Python code | 357,785 | <p>I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.</p>
<p>Does anyone have a preferred way to do Python code folding in Vim? I.e, </p>
<ul>
<li>Do you have a particular Vim plugin that you use and like?</li>
<li>Do you use manual folding or do you place markers in comments?</li>
<li>Any other recommended ways to do code folding for Python in Vim?</li>
</ul>
| 83 | 2008-12-10T22:10:45Z | 33,940,401 | <p>Yet another plugin for folding Python code. Rather simple, handling docstrings, and on the GitHub:</p>
<p><a href="https://github.com/tmhedberg/SimpylFold" rel="nofollow">SimpylFold</a></p>
<p>Enjoy!</p>
| 1 | 2015-11-26T13:51:00Z | [
"python",
"vim",
"folding"
] |
A small question about python's variable scope | 357,810 | <p>I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:</p>
<pre><code>def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
</code></pre>
| 1 | 2008-12-10T22:20:07Z | 357,853 | <p>your example program works, because the two instances of 'good' are different variables (you just happen to have both variables with the same name). The following code is exactly the same:</p>
<pre><code>def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return great
</code></pre>
| 2 | 2008-12-10T22:35:55Z | [
"python",
"variables",
"scope"
] |
A small question about python's variable scope | 357,810 | <p>I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:</p>
<pre><code>def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
</code></pre>
| 1 | 2008-12-10T22:20:07Z | 357,855 | <p>The scope of functions <code>hello</code> and <code>hi</code> are entirely different. They do not have any variables in common.</p>
<p>Note that the result of calling <code>hi(x,y)</code> is some object. You save that object with the name <code>good</code> in the function <code>hello</code>.</p>
<p>The variable named <code>good</code> in <code>hello</code> is a different variable, unrelated to the variable named <code>good</code> in the function <code>hi</code>.</p>
<p>They're spelled the same, but the exist in different namespaces. To prove this, change the spelling the <code>good</code> variable in one of the two functions, you'll see that things still work.</p>
<p><hr /></p>
<p>Edit. Follow-up: "so what should i do if i want use the result of <code>hi</code> function in <code>hello</code> function?"</p>
<p>Nothing unusual. Look at <code>hello</code> closely.</p>
<pre><code>def hello(x,y):
fordf150 = hi(y,x)
"then do somethings,and use the variable 'fordf150'."
return something
def hi( ix, iy ):
"compute some value, good."
return good
</code></pre>
<p>Some script evaluates <code>hello( 2, 3)</code>.</p>
<ol>
<li><p>Python creates a new namespace for the evaluation of <code>hello</code>.</p></li>
<li><p>In <code>hello</code>, <code>x</code> is bound to the object <code>2</code>. Binding is done position order.</p></li>
<li><p>In <code>hello</code>, <code>y</code> is bound to the object <code>3</code>.</p></li>
<li><p>In <code>hello</code>, Python evaluates the first statement, <code>fordf150 = hi( y, x )</code>, <code>y</code> is 3, <code>x</code> is 2.</p>
<p>a. Python creates a new namespace for the evaluation of <code>hi</code>.</p>
<p>b. In <code>hi</code>, <code>ix</code> is bound to the object <code>3</code>. Binding is done position order.</p>
<p>c. In <code>hi</code>, <code>iy</code> is bound to the object <code>2</code>.</p>
<p>d. In <code>hi</code>, something happens and <code>good</code> is bound to some object, say <code>3.1415926</code>.</p>
<p>e. In <code>hi</code>, a <code>return</code> is executed; identifying an object as the value for <code>hi</code>. In this case, the object is named by <code>good</code> and is the object <code>3.1415926</code>.</p>
<p>f. The <code>hi</code> namespace is discarded. <code>good</code>, <code>ix</code> and <code>iy</code> vanish. The object (<code>3.1415926</code>), however, remains as the value of evaluating <code>hi</code>.</p></li>
<li><p>In <code>hello</code>, Python finishes the first statement, <code>fordf150 = hi( y, x )</code>, <code>y</code> is 3, <code>x</code> is 2. The value of <code>hi</code> is <code>3.1415926</code>.</p>
<p>a. <code>fordf150</code> is bound to the object created by evaluating <code>hi</code>, <code>3.1415926</code>.</p></li>
<li><p>In <code>hello</code>, Python moves on to other statements.</p></li>
<li><p>At some point <code>something</code> is bound to an object, say, <code>2.718281828459045</code>.</p></li>
<li><p>In <code>hello</code>, a <code>return</code> is executed; identifying an object as the value for <code>hello</code>. In this case, the object is named by <code>something</code> and is the object <code>2.718281828459045 </code>.</p></li>
<li><p>The namespace is discarded. <code>fordf150</code> and <code>something</code> vanish, as do <code>x</code> and <code>y</code>. The object (<code>2.718281828459045 </code>), however, remains as the value of evaluating <code>hello</code>.</p></li>
</ol>
<p>Whatever program or script called <code>hello</code> gets the answer.</p>
| 5 | 2008-12-10T22:36:30Z | [
"python",
"variables",
"scope"
] |
A small question about python's variable scope | 357,810 | <p>I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:</p>
<pre><code>def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
</code></pre>
| 1 | 2008-12-10T22:20:07Z | 357,858 | <p>The "hello" function doesn't mind you calling the "hi" function which is hasn't been defined yet, provided you don't try to actually use the "hello" function until after the both functions have been defined.</p>
| 1 | 2008-12-10T22:37:05Z | [
"python",
"variables",
"scope"
] |
A small question about python's variable scope | 357,810 | <p>I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:</p>
<pre><code>def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
</code></pre>
| 1 | 2008-12-10T22:20:07Z | 358,013 | <p>If you want to define a variable to the global namespace from inside a function, and thereby make it accessible by other functions in this space, you can use the global keyword. Here's some examples</p>
<pre><code>varA = 5 #A normal declaration of an integer in the main "global" namespace
def funcA():
print varA #This works, because the variable was defined in the global namespace
#and functions have read access to this.
def changeA():
varA = 2 #This however, defines a variable in the function's own namespace
#Because of this, it's not accessible by other functions.
#It has also replaced the global variable, though only inside this function
def newVar():
global varB #By using the global keyword, you assign this variable to the global namespace
varB = 5
def funcB():
print varB #Making it accessible to other functions
</code></pre>
<p>Conclusion: variables defined in a function stays in the function's namespace. It still has access to the global namespace for reading only, unless the variable has been called with the global keyword.</p>
<p>The term global isn't entirely global as it may seem at first. It's practically only a link to the lowest namespace in the file you're working in. Global keywords cannot be accessed in another module.</p>
<p>As a mild warning, this may be considered to be less "good practice" by some.</p>
| 3 | 2008-12-10T23:35:45Z | [
"python",
"variables",
"scope"
] |
A small question about python's variable scope | 357,810 | <p>I am a beginner of python and have a question, very confusing for me.
If I define a function first but within the function I have to use a variable which is defined in another function below, can I do it like this? Or how can I import the return things of another function into a function?
for example:</p>
<pre><code>def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
</code></pre>
| 1 | 2008-12-10T22:20:07Z | 358,041 | <p>More details on the python scoping rules are here :</p>
<p><a href="http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules#292502">Short Description of Python Scoping Rules</a></p>
| 2 | 2008-12-10T23:54:34Z | [
"python",
"variables",
"scope"
] |
Problem with Python implementation of Conway's Game of Life | 357,968 | <p>I am working on <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Conway's Game of Life</a> currently and have gotten stuck. My code doesn't work.</p>
<p>When I run my code in GUI, it says:</p>
<pre>
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
</pre>
<p>Here is my code:</p>
<pre><code>'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
</code></pre>
<p>I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about <code>import "neighbours"</code> to <code>function "apply_rules"</code>, is that right way to do this?</p>
| 0 | 2008-12-10T23:17:02Z | 357,982 | <p>A cursory glance shows that your <code>number_neighbors</code> indices are off.</p>
<p>Also, you never initialize <code>neighbors</code>.</p>
<p><b>Response to Comment:</b></p>
<pre><code>def number_neighbours(universe_array,iy,ix):
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
</code></pre>
<p>You say, <code>neighbors +=1</code>, which means add 1 to <code>neighbors</code>, but you never told it to start at 0, so it doesn't know what do add 1 to. </p>
<p>Also, notice the first and 3rd lines are exactly the same. I'm pretty sure this is not what you intended. That's what I meant by "your indices are off".</p>
<p><b> Response to Comment 2: </b>
<code>apply_rules</code> has several lines where you want to assign a value to something (which is '='), but you use '==' instead.</p>
| 2 | 2008-12-10T23:20:30Z | [
"python"
] |
Problem with Python implementation of Conway's Game of Life | 357,968 | <p>I am working on <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Conway's Game of Life</a> currently and have gotten stuck. My code doesn't work.</p>
<p>When I run my code in GUI, it says:</p>
<pre>
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
</pre>
<p>Here is my code:</p>
<pre><code>'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
</code></pre>
<p>I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about <code>import "neighbours"</code> to <code>function "apply_rules"</code>, is that right way to do this?</p>
| 0 | 2008-12-10T23:17:02Z | 357,994 | <p>This is an extremely low-grade lazy question, but your number_neighbours function is broken, it checks universe_array[iy,ix-1] twice (and hence omits a check it should be doing).</p>
| 0 | 2008-12-10T23:24:28Z | [
"python"
] |
Problem with Python implementation of Conway's Game of Life | 357,968 | <p>I am working on <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Conway's Game of Life</a> currently and have gotten stuck. My code doesn't work.</p>
<p>When I run my code in GUI, it says:</p>
<pre>
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
</pre>
<p>Here is my code:</p>
<pre><code>'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
</code></pre>
<p>I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about <code>import "neighbours"</code> to <code>function "apply_rules"</code>, is that right way to do this?</p>
| 0 | 2008-12-10T23:17:02Z | 358,020 | <p>You're trying to increment a variable that doesn't exist yet. Python can't increment something if it doesn't know what is. Try adding the following line at the top of your def number_neighbours function.</p>
<pre><code>neighbours = 0
</code></pre>
| 3 | 2008-12-10T23:39:28Z | [
"python"
] |
Problem with Python implementation of Conway's Game of Life | 357,968 | <p>I am working on <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow">Conway's Game of Life</a> currently and have gotten stuck. My code doesn't work.</p>
<p>When I run my code in GUI, it says:</p>
<pre>
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
</pre>
<p>Here is my code:</p>
<pre><code>'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
</code></pre>
<p>I am a beginner at Python, and I don't know how to fix the error. I am a little bit confused about <code>import "neighbours"</code> to <code>function "apply_rules"</code>, is that right way to do this?</p>
| 0 | 2008-12-10T23:17:02Z | 358,029 | <p>Well, I guess that you are also quite new to programming <em>per se</em>, otherwise you should not have any problems in interpreting that simple error message.</p>
<p>I'll help you dissect it:</p>
<ul>
<li>First, all "current" line numbers of your project's files are displayed, in calling order.</li>
<li>Then, it shows you the function in which the error occured: <code>number_neighbours</code></li>
<li>Then, it shows you the contents of the line that contains the error: <code>neighbours+=1</code></li>
<li>Finally, it tells you what the problem with that line is: <code>UnboundLocalError: local variable 'neighbours' referenced before assignment</code></li>
</ul>
<p>Now, what does that mean? Let's see what the <code>+=</code> operator does: it adds something to the current value of <code>neighbours</code>. That means that it reads the current value, adds something to it, and finally stores it back. "Reading" is called "reference" with respect to variables.</p>
<p>What is the current value of <code>neighbours</code>? Well, it has never been used before, so it doesn't have any value -- there has never been a value assigned to it. Adding something to 'no value' is not a sensible thing to do. I guess that you expect it to have the value 0, but you have to tell it to your interpreter. To do this, add the following statement before, at the start of your function: <code>neighbours = 0</code></p>
| 13 | 2008-12-10T23:44:47Z | [
"python"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 358,012 | <p>Java uses anonymous classes mostly to imitate closures or simply code blocks. Since in Python you can easily pass around methods there's no need for a construct as clunky as anonymous inner classes:</p>
<pre><code>def printStuff():
print "hello"
def doit(what):
what()
doit(printStuff)
</code></pre>
<p>Edit: I'm aware that this is not what is needed in this special case. I just described the most common python solution to the problem most commonly by anonymous inner classes in Java.</p>
| 13 | 2008-12-10T23:35:43Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 358,035 | <p>In python you have anonymous functions, declared using lambda statement. I do not like them very much - they are not so readable, and have limited functionality.</p>
<p>However, what you are talking about may be implemented in python with a completely different approach:</p>
<pre><code>class a(object):
def meth_a(self):
print "a"
def meth_b(obj):
print "b"
b = a()
b.__class__.meth_a = meth_b
</code></pre>
| 2 | 2008-12-10T23:49:53Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 358,042 | <p>Python probably has better ways to solve your problem. If you could provide more specific details of what you want to do it would help.</p>
<p>For example, if you need to change the method being called in a specific point in code, you can do this by passing the function as a parameter (functions are first class objects in python, you can pass them to functions, etc). You can also create anonymous <code>lambda</code> functions (but they're restricted to a single expression).</p>
<p>Also, since python is very dynamic, you can change methods of an object after it's been created <code>object.method1 = alternative_impl1</code>, although it's actually a bit more complicated, see <a href="http://stackoverflow.com/questions/357997/python-does-have-something-like-anonymous-inner-classes-of-java#358055">gnud's answer</a></p>
| 5 | 2008-12-10T23:54:47Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 358,055 | <p>You can accomplish this in three ways:</p>
<ol>
<li>Proper subclass (of course)</li>
<li>a custom method that you invoke with the object as an argument</li>
<li>(what you probably want) -- adding a new method to an object (or replacing an existing one).</li>
</ol>
<p>Example of option 3 (edited to remove use of "new" module -- It's deprecated, I did not know ):</p>
<pre><code>import types
class someclass(object):
val = "Value"
def some_method(self):
print self.val
def some_method_upper(self):
print self.val.upper()
obj = someclass()
obj.some_method()
obj.some_method = types.MethodType(some_method_upper, obj)
obj.some_method()
</code></pre>
| 11 | 2008-12-11T00:01:54Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 358,062 | <p>Well, classes are first class objects, so you can create them in methods if you want. e.g.</p>
<pre><code>from optparse import OptionParser
def make_custom_op(i):
class MyOP(OptionParser):
def exit(self):
print 'custom exit called', i
return MyOP
custom_op_class = make_custom_op(3)
custom_op = custom_op_class()
custom_op.exit() # prints 'custom exit called 3'
dir(custom_op) # shows all the regular attributes of an OptionParser
</code></pre>
<p>But, really, why not just define the class at the normal level? If you need to customise it, put the customisation in as arguments to <code>__init__</code>.</p>
<p>(edit: fixed typing errors in code)</p>
| 10 | 2008-12-11T00:05:13Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 359,651 | <p>Python doesn't support this directly (anonymous classes) but because of its terse syntax it isn't really necessary:</p>
<pre><code>class MyOptionParser(OptionParser):
def exit(self, status=0, msg=None):
# body of method
p = MyOptionParser()
</code></pre>
<p>The only downside is you add MyOptionParser to your namespace, but as John Fouhy pointed out, you can hide that inside a function if you are going to do it multiple times.</p>
| 6 | 2008-12-11T15:06:37Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 3,915,434 | <p>You can use the <a href="http://docs.python.org/library/functions.html#type"><code>type(name, bases, dict)</code></a> builtin function to create classes on the fly. For example:</p>
<pre><code>op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" })
op().foo()
</code></pre>
<p>Since OptionParser isn't a new-style class, you have to explicitly include <code>object</code> in the list of base classes.</p>
| 22 | 2010-10-12T13:53:02Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 6,175,128 | <p>You can always hide class by variables:</p>
<pre><code> class var(...):
pass
var = var()
</code></pre>
<p>instead of</p>
<pre><code> var = new ...() {};
</code></pre>
| 0 | 2011-05-30T10:28:57Z | [
"python",
"class",
"anonymous-class"
] |
Does Python have something like anonymous inner classes of Java? | 357,997 | <p>In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.</p>
<p>Suppose that you want create a subclass of <code>OptionParser</code> that overrides only a single method (for example <code>exit()</code>). In Java you can write something like this:</p>
<pre><code>new OptionParser () {
public void exit() {
// body of the method
}
};
</code></pre>
<p>This piece of code creates a anonymous class that extends <code>OptionParser</code> and override only the <code>exit()</code> method.</p>
<p>There is a similar idiom in Python? Which idiom is used in these circumstances?</p>
| 28 | 2008-12-10T23:26:57Z | 12,384,223 | <pre><code>#!/usr/bin/env python
import os;os.system("""ruby << 'GOZER'
anonymous_class = Class.new do
def hi(name)
puts "Hello: #{name}."
end
def too_late(message)
exit 1
end
end
anonymous_ghoul = anonymous_class.new
anonymous_ghoul.hi("Egon Spengler")
anonymous_ghoul.too_late <<-quote
There's something very import I forgot to tell you.
Don't cross the streams.
It would be bad.
quote
GOZER""")
</code></pre>
| -4 | 2012-09-12T08:38:36Z | [
"python",
"class",
"anonymous-class"
] |
Can I use chart modules with wxpython? | 358,189 | <p>Is it possible to use any chart modules with wxpython? And are there any good ones out there?</p>
<p>I'm thinking of the likes of PyCha (<a href="http://www.lorenzogil.com/projects/pycha/">http://www.lorenzogil.com/projects/pycha/</a>) or any equivalent. Many modules seem to require PyCairo, but I can't figure out if I can use those with my wxpython app.</p>
<p>My app has a notebook pane, and I'd like to place the chart inside it. The chart has to be dynamic -- ie the user can choose what kind of data to view -- so I'm guessing modules that make chart images are out.</p>
<p>Just for clarity, by charts I mean things like pies, lines and bars etc.</p>
| 5 | 2008-12-11T01:15:41Z | 358,328 | <p>I recently revisited <a href="http://matplotlib.sourceforge.net/index.html" rel="nofollow">matplotlib</a>, and am pretty happy with the results.
If you're on windows, there are windows installers available to make your installation process a little less painful.</p>
<p>One potential drawback though is that it requires <a href="http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103" rel="nofollow">numpy</a> to be installed.</p>
<p>I don't have experience with the interactivity of it, but it does support <a href="http://matplotlib.sourceforge.net/users/event_handling.html?highlight=wxpython" rel="nofollow">event handling</a>.</p>
| 3 | 2008-12-11T02:54:33Z | [
"python",
"wxpython"
] |
Can I use chart modules with wxpython? | 358,189 | <p>Is it possible to use any chart modules with wxpython? And are there any good ones out there?</p>
<p>I'm thinking of the likes of PyCha (<a href="http://www.lorenzogil.com/projects/pycha/">http://www.lorenzogil.com/projects/pycha/</a>) or any equivalent. Many modules seem to require PyCairo, but I can't figure out if I can use those with my wxpython app.</p>
<p>My app has a notebook pane, and I'd like to place the chart inside it. The chart has to be dynamic -- ie the user can choose what kind of data to view -- so I'm guessing modules that make chart images are out.</p>
<p>Just for clarity, by charts I mean things like pies, lines and bars etc.</p>
| 5 | 2008-12-11T01:15:41Z | 358,493 | <p>matplotlib does embed quite well in <a href="http://www.scipy.org/Cookbook/Matplotlib/EmbeddingInWx" rel="nofollow">wxpython</a>. I have only used it in Tkinter, which went smoothly for me. I like the optional toolbar that allows direct manipulation of the plot (resizing and panning and such)</p>
| 1 | 2008-12-11T05:11:51Z | [
"python",
"wxpython"
] |
Can I use chart modules with wxpython? | 358,189 | <p>Is it possible to use any chart modules with wxpython? And are there any good ones out there?</p>
<p>I'm thinking of the likes of PyCha (<a href="http://www.lorenzogil.com/projects/pycha/">http://www.lorenzogil.com/projects/pycha/</a>) or any equivalent. Many modules seem to require PyCairo, but I can't figure out if I can use those with my wxpython app.</p>
<p>My app has a notebook pane, and I'd like to place the chart inside it. The chart has to be dynamic -- ie the user can choose what kind of data to view -- so I'm guessing modules that make chart images are out.</p>
<p>Just for clarity, by charts I mean things like pies, lines and bars etc.</p>
| 5 | 2008-12-11T01:15:41Z | 365,046 | <p>Use matplotlib. It integrates nicely with wxPython. <a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/" rel="nofollow">Here's a sample</a> of an interactive chart with wxPython and matplotlib. </p>
| 1 | 2008-12-13T09:40:03Z | [
"python",
"wxpython"
] |
log4j with timestamp per log entry | 358,225 | <p>this is my log output</p>
<pre><code>INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting [email protected]
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or no attachments supported
INFO main digestemails - updating database
INFO main digestemails - email -> COMPLETED folder
INFO main digestemails -
</code></pre>
<p>I would like a time stamp per log message ie</p>
<pre><code>INFO 2008-12-25 13:14:00 digestemails - email -> COMPLETED folder
</code></pre>
<p>here is my log4j config file</p>
<pre><code>log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=c:\\development\\DCMail\\logs\\digestlogfolder\\digest-logfile.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
</code></pre>
<p>How do I do it?</p>
| 41 | 2008-12-11T01:44:39Z | 358,247 | <p>Use %d in your PatternLayout.</p>
<p>Also %d can take a format pattern as in %d{dd MMM yyyy HH:mm:ss,SSS} you can pick and choose the elements that you want. When the format pattern is omitted the date will be in ISO8601 format.</p>
| 77 | 2008-12-11T01:59:03Z | [
"java",
"python",
"log4j",
"jython"
] |
log4j with timestamp per log entry | 358,225 | <p>this is my log output</p>
<pre><code>INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting [email protected]
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or no attachments supported
INFO main digestemails - updating database
INFO main digestemails - email -> COMPLETED folder
INFO main digestemails -
</code></pre>
<p>I would like a time stamp per log message ie</p>
<pre><code>INFO 2008-12-25 13:14:00 digestemails - email -> COMPLETED folder
</code></pre>
<p>here is my log4j config file</p>
<pre><code>log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=c:\\development\\DCMail\\logs\\digestlogfolder\\digest-logfile.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
</code></pre>
<p>How do I do it?</p>
| 41 | 2008-12-11T01:44:39Z | 358,372 | <p>You can find more conversion characters usage in log4j javadoc.For example, at <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html" rel="nofollow">http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html</a>.</p>
| 5 | 2008-12-11T03:29:46Z | [
"java",
"python",
"log4j",
"jython"
] |
log4j with timestamp per log entry | 358,225 | <p>this is my log output</p>
<pre><code>INFO main digestemails - process inbox
INFO main digestemails - checking for emails in c:\development\DCMail\email\KN-Source
INFO main digestemails - digesting [email protected]
INFO main digestemails - extracting attachments
INFO main digestemails - no attachments or no attachments supported
INFO main digestemails - updating database
INFO main digestemails - email -> COMPLETED folder
INFO main digestemails -
</code></pre>
<p>I would like a time stamp per log message ie</p>
<pre><code>INFO 2008-12-25 13:14:00 digestemails - email -> COMPLETED folder
</code></pre>
<p>here is my log4j config file</p>
<pre><code>log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=c:\\development\\DCMail\\logs\\digestlogfolder\\digest-logfile.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
</code></pre>
<p>How do I do it?</p>
| 41 | 2008-12-11T01:44:39Z | 358,641 | <p>A extract from my properties file</p>
<pre><code>log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p (%t) [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=C:/log/client.log
log4j.appender.logfile.MaxFileSize=5MB
log4j.appender.logfile.MaxBackupIndex=0
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
</code></pre>
| 13 | 2008-12-11T07:45:42Z | [
"java",
"python",
"log4j",
"jython"
] |
Keeping a variable around from post to get? | 358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| 0 | 2008-12-11T03:50:02Z | 358,425 | <p>I don't know specifically about the google app engine, but normally, here's what happens:</p>
<p>The server would have some kind of thread pool. Every time an http request is sent to the server, a thread is selected from the pool or created.</p>
<p>In that thread an instance of some kind of controller object will be created. This object will decide what to do with the request (like instantiating other classes and preprocessing the http request parameters). Usually, this object is the core of web frameworks. The request parameters are also resent by the browser every time (the server cannot guess what the browser wants).</p>
<p>Web servers usually have state stores for objects in a permanent or a session state. The session is represented by a unique user (usually by a cookie or a GUID in the url), which expires after a certain time.</p>
<p>Now in your case, you would need to take the values you got from your first function, store that in the session store and in the second function, get those values back from the session store.</p>
<p>Another solution would be to send the items back to the page as url parameters in your generated HTML from the first function and then you would get those back "as usual" from your second function.</p>
| 0 | 2008-12-11T04:09:50Z | [
"python",
"google-app-engine",
"post",
"get"
] |
Keeping a variable around from post to get? | 358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| 0 | 2008-12-11T03:50:02Z | 358,613 | <p>It is not a problem of how the instances are managed. Because HTTP is stateless, your program is, virtually, stateless too. (For long running processes, like GAE, it is possible to make it otherwise, but I am not sure you would need this complexity here)</p>
<p>You haven't supplied any code, but I am assuming you get a POST and then you <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="nofollow">redirect</a> to results (which is a GET). So it should be easy to preserve the parameter:</p>
<pre><code>def save_foo(request):
if request.method == 'POST':
save(request.POST)
return HttpRedirect(reverse(
'Some_Target',
{'bar': 'baz', 'foo': request.POST['foo']}))
else:
# do something else
</code></pre>
<p>This view, in case of a POST, casues the client to issue a GET request to whatever URL is aliased <code>Some_Target</code>. And this GET will include <code>foo</code> parameter from the POST.</p>
<p>This solution is for a single view. If you need this behaviour project-wise you can use a middleware for it. And this time caching the variable makes sense.</p>
<p>There are two things that make me a little uncomfortable with this approach:</p>
<ol>
<li>Mixing GET and POST parameters. GET parameters should be used for instructions with no side effects, like filtering. POST parameter should be used for insructions with side effects, ie modifying the data. Moving a parameter from POST to get should be avoided IMHO.</li>
<li>If we need persistence, using object instances (or function scopes as in my example) is usually not a good idea.
<ol>
<li>If it is non sensitive information with with lower retention needs <code>cookies</code> are the way to go. They are a mechanism of persistence on the client side, so you can just grab them form the request and unless you change them they are retained (until expiration of course.)</li>
<li>If you need more control over retention you should use local persistence mechanisms. Server cache (of any kind), filesystem, database... Then of course you will need to filter per user manually.</li>
</ol></li>
</ol>
<p>In any case I would avoid caching on instances.</p>
| 1 | 2008-12-11T07:12:22Z | [
"python",
"google-app-engine",
"post",
"get"
] |
Keeping a variable around from post to get? | 358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| 0 | 2008-12-11T03:50:02Z | 358,757 | <p>HTTP is stateless, so you have no (built-in) way of knowing if the user that loads one page is the same user that loaded another. Further, even if you do know that, thanks to session cookies, for example, you have no way of telling if the browser window they're loading the subsequent page in is the same one they loaded the prior page in. The user could have multiple tabs accessing your site, and you don't want one page's state change to clobber another's.</p>
<p>With that in mind, your best option is to include query parameters in the link to the page being fetched with GET, encoding the variables you want to send to the 'get' page (make sure they're not sensitive, since the user can modify them!). Then you can access them through self.request.GET in the get request.</p>
| 1 | 2008-12-11T09:18:31Z | [
"python",
"google-app-engine",
"post",
"get"
] |
Keeping a variable around from post to get? | 358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| 0 | 2008-12-11T03:50:02Z | 358,805 | <p>Why not just use memcache to temporarily store the variable, and then redirect to the POST URL? That seems like the easiest solution. </p>
| 0 | 2008-12-11T09:41:01Z | [
"python",
"google-app-engine",
"post",
"get"
] |
Keeping a variable around from post to get? | 358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| 0 | 2008-12-11T03:50:02Z | 359,034 | <p>What you're talking about is establishing a "session". That is, a way to remember the user and the state of their transaction.</p>
<p>There are several ways of tackling this, all of which rely on techniques for remembering that you're in a session in the first place.</p>
<p>HTTP provides you no help. You have to find some place to save session state on the server, and some place to record session identification on the client. The two big techniques are</p>
<ul>
<li><p>Use a cookie to identify the session. Seamless and silent.</p></li>
<li><p>Use a query string in the URL to identify the session. Obvious because you have a <code>?sessionid=SomeSessionGUID</code> in your URL's. This exposes a lot and makes bookmarking annoying. After the session is cleaned up, you still have this session id floating around in people's bookmarks.</p></li>
<li><p>In a limited way, you can also use hidden fields in a form. This only works if you have forms on every page. Not always true.</p></li>
</ul>
<p>Here's how it plays out in practice.</p>
<ol>
<li><p>GET response. Check for the cookie in the header.</p>
<p>a. No cookie. First time user. Create a session. Save it somewhere (memory, file, database). Put the unique ID into a cookie. Respond knowing this is their first time.</p>
<p>b. Cookie. Been here recently. Try to get the cookie. </p>
<ul>
<li><p>FInd the session object. Respond using information in the cookie.</p></li>
<li><p>Drat. No session. Old cookie. Create a new one and act like this is their first visit.</p></li>
</ul></li>
<li><p>POST response. Check for the cookie in the header.</p>
<p>a. No cookie. WTF? Stupid kids. Get off my lawn! Someone bookmarked a POST or is trying to mess with your head. Respond as if it was a first-time GET.</p>
<p>b. Cookie. Excellent. Get the cookie. </p>
<ul>
<li><p>Find the session object. Find the thing you need in the session object. Respond.</p></li>
<li><p>Drat. No session. Old cookie. Create a new one and respond as if was a first-time GET.</p></li>
</ul></li>
</ol>
<p>You can do the same thing with a query string instead of a cookie. Or a hidden field on a form. </p>
| 3 | 2008-12-11T11:24:44Z | [
"python",
"google-app-engine",
"post",
"get"
] |
Keeping a variable around from post to get? | 358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| 0 | 2008-12-11T03:50:02Z | 360,292 | <p>OK -- Thanks everyone. </p>
<p>I'll try some of these ideas out, soon, and get back to you all. </p>
<p>It seems I can work around some these things by doing a lot of writing and reading from the datastore*, but I thought there might be an easier way of keeping that instance of the class around (I'm trying to use my known techniques in a web framework that I don't completely get yet). </p>
<p>*For instance, creating a unique record based on the data in the POST, and letting some variables "tag along". Is this a bad practice? </p>
| 0 | 2008-12-11T18:02:19Z | [
"python",
"google-app-engine",
"post",
"get"
] |
XMODEM for python | 358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| 2 | 2008-12-11T04:49:04Z | 358,480 | <p>I think youâre stuck with rolling your own.</p>
<p>You might be able to use <a href="http://linux.about.com/library/cmd/blcmdl1_sz.htm" rel="nofollow">sz</a>, which implements X/Y/ZMODEM. You could call out to the binary, or port the necessary code to Python.</p>
| 1 | 2008-12-11T04:56:57Z | [
"python",
"serial-port",
"file-transfer",
"xmodem"
] |
XMODEM for python | 358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| 2 | 2008-12-11T04:49:04Z | 358,509 | <p>Here is a link to <a href="http://www.programmersheaven.com/download/2167/download.aspx" rel="nofollow">XMODEM</a> documentation that will be useful if you have to write your own. It has detailed description of the original XMODEM, XMODEM-CRC and XMODEM-1K.</p>
<p>You might also find this <a href="http://www.menie.org/georges/embedded/index.html" rel="nofollow">c-code</a> of interest.</p>
| 1 | 2008-12-11T05:32:48Z | [
"python",
"serial-port",
"file-transfer",
"xmodem"
] |
XMODEM for python | 358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| 2 | 2008-12-11T04:49:04Z | 358,624 | <p>You can try using <a href="http://www.swig.org/" rel="nofollow">SWIG</a> to create Python bindings for the C libraries linked above (or any other C/C++ libraries you find online). That will allow you to use the same C API directly from Python.</p>
<p>The actual implementation will of course still be in C/C++, since SWIG merely creates bindings to the functions of interest.</p>
| 0 | 2008-12-11T07:26:04Z | [
"python",
"serial-port",
"file-transfer",
"xmodem"
] |
XMODEM for python | 358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| 2 | 2008-12-11T04:49:04Z | 705,300 | <pre><code>def xmodem_send(serial, file):
t, anim = 0, '|/-\\'
serial.setTimeout(1)
while 1:
if serial.read(1) != NAK:
t = t + 1
print anim[t%len(anim)],'\r',
if t == 60 : return False
else:
break
p = 1
s = file.read(128)
while s:
s = s + '\xFF'*(128 - len(s))
chk = 0
for c in s:
chk+=ord(c)
while 1:
serial.write(SOH)
serial.write(chr(p))
serial.write(chr(255 - p))
serial.write(s)
serial.write(chr(chk%256))
serial.flush()
answer = serial.read(1)
if answer == NAK: continue
if answer == ACK: break
return False
s = file.read(128)
p = (p + 1)%256
print '.',
serial.write(EOT)
return True
</code></pre>
| 4 | 2009-04-01T12:40:00Z | [
"python",
"serial-port",
"file-transfer",
"xmodem"
] |
XMODEM for python | 358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| 2 | 2008-12-11T04:49:04Z | 5,196,623 | <p>There is XMODEM module on PyPi. It handles both sending and receiving of data with XModem. Below is sample of its usage:</p>
<pre><code>import serial
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
from xmodem import XMODEM, NAK
from time import sleep
def readUntil(char = None):
def serialPortReader():
while True:
tmp = port.read(1)
if not tmp or (char and char == tmp):
break
yield tmp
return ''.join(serialPortReader())
def getc(size, timeout=1):
return port.read(size)
def putc(data, timeout=1):
port.write(data)
sleep(0.001) # give device time to prepare new buffer and start sending it
port = serial.Serial(port='COM5',parity=serial.PARITY_NONE,bytesize=serial.EIGHTBITS,stopbits=serial.STOPBITS_ONE,timeout=0,xonxoff=0,rtscts=0,dsrdtr=0,baudrate=115200)
port.write("command that initiates xmodem send from device\r\n")
sleep(0.02) # give device time to handle command and start sending response
readUntil(NAK)
buffer = StringIO()
XMODEM(getc, putc).recv(buffer, crc_mode = 0, quiet = 1)
contents = buffer.getvalue()
buffer.close()
readUntil()
</code></pre>
| 1 | 2011-03-04T16:37:34Z | [
"python",
"serial-port",
"file-transfer",
"xmodem"
] |
XMODEM for python | 358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| 2 | 2008-12-11T04:49:04Z | 26,754,421 | <p>There is a python module that you can use -> <a href="https://pypi.python.org/pypi/xmodem" rel="nofollow">https://pypi.python.org/pypi/xmodem</a></p>
<p>You can see the transfer protocol in <a href="http://pythonhosted.org//xmodem/xmodem.html" rel="nofollow">http://pythonhosted.org//xmodem/xmodem.html</a></p>
| 0 | 2014-11-05T10:09:10Z | [
"python",
"serial-port",
"file-transfer",
"xmodem"
] |
python, set terminal type in pexpect | 358,783 | <p>I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.</p>
<p>The problem I have, I think, is that this program uses a coloured prompt.</p>
<p>This is what I do </p>
<pre><code>import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)
</code></pre>
<p>This is the output:</p>
<pre><code>> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...
---------before------------
' \x1b[0m\x1b[8D\x1b[K\x1b[1m\x1b[34m'
---------after------------
'prompt>'
</code></pre>
<p>For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.</p>
<p>Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?</p>
<p>I am using tcsh shell</p>
| 4 | 2008-12-11T09:32:43Z | 358,794 | <p>Couldn't find anything in <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">the pexpect documentation</a> for setting terminals, but you could probably start your program explicitly with a shell, and then set the terminal type there:</p>
<pre><code>shell_cmd = 'ls -l | grep LOG > log_list.txt'
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
child.expect(pexpect.EOF)
</code></pre>
<p>You could try something like</p>
<pre><code>child = pexpect.spawn('TERM=vt100 /bin/bash', ['-c', shell_cmd])
</code></pre>
<p>You can also start bash with --norc and similar to avoid reading the initialization files. Check out the <a href="http://linux.die.net/man/1/bash" rel="nofollow">bash man page</a>.</p>
| 2 | 2008-12-11T09:38:59Z | [
"python",
"pexpect"
] |
python, set terminal type in pexpect | 358,783 | <p>I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.</p>
<p>The problem I have, I think, is that this program uses a coloured prompt.</p>
<p>This is what I do </p>
<pre><code>import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)
</code></pre>
<p>This is the output:</p>
<pre><code>> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...
---------before------------
' \x1b[0m\x1b[8D\x1b[K\x1b[1m\x1b[34m'
---------after------------
'prompt>'
</code></pre>
<p>For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.</p>
<p>Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?</p>
<p>I am using tcsh shell</p>
| 4 | 2008-12-11T09:32:43Z | 359,241 | <p>Ok, I found the answer. csl's answer set me on the right path.</p>
<p>pexpect has a "env" option which I thought I could use. like this:</p>
<pre><code>a = pexpect.spawn('program', env = {"TERM": "dumb"})
</code></pre>
<p>But this spawns a new shell which does not work for me, our development environment
depends on a lot of environmental variables :/</p>
<p>But if I do this before spawning a shell:</p>
<pre><code>import os
os.environ["TERM"] = "dumb"
</code></pre>
<p>I change the current "TERM" and "dumb" does not support colours, which fixed my issue.</p>
| 7 | 2008-12-11T12:52:34Z | [
"python",
"pexpect"
] |
Execute Commands Sequentially in Python | 359,347 | <p>I would like to execute multiple commands in a row:</p>
<p>ie (just to illustrate my need):</p>
<p><strong>cmd</strong> (the shell)</p>
<p>then</p>
<p><strong>cd dir</strong></p>
<p>and</p>
<p><strong>ls</strong></p>
<p>and read the result of the ls.</p>
<p>Any idea with subprocess module ?</p>
<p>UPDATE:</p>
<p>cd dir and ls are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, i would like one subprocess shell and the ability to launch many commands on it.</p>
| 13 | 2008-12-11T13:30:23Z | 359,355 | <p>Yes, the <code><a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess.Popen</a>()</code> function supports a <code>cwd</code> keyword argument, with which you can set the directory it runs the process in.</p>
<p>I guess the first step, the shell, is not needed, if all you want is to run <code>ls</code>, there's no need to run it through a shell.</p>
<p>Of course, you could also just pass the desired directory as an argument to <code>ls</code>.</p>
<p>Update: it might be worth noting that for typical shells, <code>cd</code> is implemented in the shell itself, it is not an external command on disk. This is because it needs to change the process' current directory, which must be done from within the process. Since commands run as child processed, spawned by the shell, they cannot do this.</p>
| 2 | 2008-12-11T13:35:39Z | [
"python",
"windows",
"subprocess"
] |
Execute Commands Sequentially in Python | 359,347 | <p>I would like to execute multiple commands in a row:</p>
<p>ie (just to illustrate my need):</p>
<p><strong>cmd</strong> (the shell)</p>
<p>then</p>
<p><strong>cd dir</strong></p>
<p>and</p>
<p><strong>ls</strong></p>
<p>and read the result of the ls.</p>
<p>Any idea with subprocess module ?</p>
<p>UPDATE:</p>
<p>cd dir and ls are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, i would like one subprocess shell and the ability to launch many commands on it.</p>
| 13 | 2008-12-11T13:30:23Z | 359,432 | <p>Finding 'bar' in every file whose name contains 'foo':</p>
<pre><code>from subprocess import Popen, PIPE
find_process = Popen(['find', '-iname', '*foo*'], stdout=PIPE)
grep_process = Popen(['xargs', 'grep', 'bar'], stdin=find_process.stdout, stdout=PIPE)
out, err = grep_process.communicate()
</code></pre>
<p>'out' and 'err' are string objects containing the standard output and, eventually, the error output.</p>
| 1 | 2008-12-11T13:59:46Z | [
"python",
"windows",
"subprocess"
] |
Execute Commands Sequentially in Python | 359,347 | <p>I would like to execute multiple commands in a row:</p>
<p>ie (just to illustrate my need):</p>
<p><strong>cmd</strong> (the shell)</p>
<p>then</p>
<p><strong>cd dir</strong></p>
<p>and</p>
<p><strong>ls</strong></p>
<p>and read the result of the ls.</p>
<p>Any idea with subprocess module ?</p>
<p>UPDATE:</p>
<p>cd dir and ls are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, i would like one subprocess shell and the ability to launch many commands on it.</p>
| 13 | 2008-12-11T13:30:23Z | 359,506 | <p>There is an easy way to execute a sequence of commands.</p>
<p>Use the following in <code>subprocess.Popen</code></p>
<pre><code>"command1; command2; command3"
</code></pre>
<p>Or, if you're stuck with windows, you have several choices.</p>
<ul>
<li><p>Create a temporary ".BAT" file, and provide this to <code>subprocess.Popen</code></p></li>
<li><p>Create a sequence of commands with "\n" separators in a single long string.</p></li>
</ul>
<p>Use """s, like this.</p>
<pre><code>"""
command1
command2
command3
"""
</code></pre>
<p>Or, if you must do things piecemeal, you have to do something like this.</p>
<pre><code>class Command( object ):
def __init__( self, text ):
self.text = text
def execute( self ):
self.proc= subprocess.Popen( ... self.text ... )
self.proc.wait()
class CommandSequence( Command ):
def __init__( self, *steps ):
self.steps = steps
def execute( self ):
for s in self.steps:
s.execute()
</code></pre>
<p>That will allow you to build a sequence of commands.</p>
| 17 | 2008-12-11T14:23:17Z | [
"python",
"windows",
"subprocess"
] |
Execute Commands Sequentially in Python | 359,347 | <p>I would like to execute multiple commands in a row:</p>
<p>ie (just to illustrate my need):</p>
<p><strong>cmd</strong> (the shell)</p>
<p>then</p>
<p><strong>cd dir</strong></p>
<p>and</p>
<p><strong>ls</strong></p>
<p>and read the result of the ls.</p>
<p>Any idea with subprocess module ?</p>
<p>UPDATE:</p>
<p>cd dir and ls are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, i would like one subprocess shell and the ability to launch many commands on it.</p>
| 13 | 2008-12-11T13:30:23Z | 359,737 | <p>To do that, you would have to:</p>
<ul>
<li>supply the <code>shell=True</code> argument in the <code>subprocess.Popen</code> call, and</li>
<li>separate the commands with:
<ul>
<li><code>;</code> if running under a *nix shell (bash, ash, sh, ksh, csh, tcsh, zsh etc)</li>
<li><code>&</code> if running under the <code>cmd.exe</code> of Windows</li>
</ul></li>
</ul>
| 18 | 2008-12-11T15:35:32Z | [
"python",
"windows",
"subprocess"
] |
Execute Commands Sequentially in Python | 359,347 | <p>I would like to execute multiple commands in a row:</p>
<p>ie (just to illustrate my need):</p>
<p><strong>cmd</strong> (the shell)</p>
<p>then</p>
<p><strong>cd dir</strong></p>
<p>and</p>
<p><strong>ls</strong></p>
<p>and read the result of the ls.</p>
<p>Any idea with subprocess module ?</p>
<p>UPDATE:</p>
<p>cd dir and ls are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, i would like one subprocess shell and the ability to launch many commands on it.</p>
| 13 | 2008-12-11T13:30:23Z | 32,923,576 | <p>below python script have 3 function what you went just excute:</p>
<pre><code>import sys
import subprocess
def cd(self,line):
proc1 = subprocess.Popen(['cd'],stdin=subprocess.PIPE)
proc1.communicate()
def ls(self,line):
proc2 = subprocess.Popen(['ls','-l'],stdin=subprocess.PIPE)
proc2.communicate()
def dir(silf,line):
proc3 = subprocess.Popen(['cd',args],stdin=subprocess.PIPE)
proc3.communicate(sys.argv[1])
</code></pre>
| 1 | 2015-10-03T14:18:30Z | [
"python",
"windows",
"subprocess"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.