title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
email body from a parsed email object in jython | 280,207 | <p>I have an object.</p>
<pre><code> fp = open(self.currentEmailPath, "rb")
p = email.Parser.Parser()
self._currentEmailParsedInstance= p.parse(fp)
fp.close()
</code></pre>
<p>self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML....</p>
<p>How do I do it?</p>
<hr>
<p>something like this? </p>
<pre><code> newmsg=self._currentEmailParsedInstance.get_payload()
body=newmsg[0].get_content....?
</code></pre>
<p>then strip the html from body.
just what is that .... method to return the actual text... maybe I mis-understand you</p>
<pre><code> msg=self._currentEmailParsedInstance.get_payload()
print type(msg)
</code></pre>
<p>output = type 'list'</p>
<hr>
<p>the email </p>
<p>Return-Path: <br>
Received: from xx.xx.net (example) by mxx3.xx.net (xxx)<br>
id 485EF65F08EDX5E12 for xxx@xx.com; Thu, 23 Oct 2008 06:07:51 +0200<br>
Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as xxxx.xxx@example.com)
id 48798D4001146189 for example.example@example-example.com; Thu, 23 Oct 2008 06:07:51 +0200<br>
From: "example" <br>
To: <br>
Subject: FW: example
Date: Thu, 23 Oct 2008 12:07:45 +0800<br>
Organization: example
Message-ID: <001601c934c4$xxxx30$a9ff460a@xxx><br>
MIME-Version: 1.0<br>
Content-Type: multipart/mixed;<br>
boundary="----=_NextPart_000_0017_01C93507.F6F64E30"<br>
X-Mailer: Microsoft Office Outlook 11<br>
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138<br>
Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA </p>
<p>This is a multi-part message in MIME format. </p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30<br>
Content-Type: multipart/alternative;<br>
boundary="----=_NextPart_001_0018_01C93507.F6F64E30" </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30<br>
Content-Type: text/plain;<br>
charset="us-ascii"<br>
Content-Transfer-Encoding: 7bit </p>
<p>From: example.example[mailto:example@example.com]<br>
Sent: Thursday, October 23, 2008 11:37 AM<br>
To: xxxx@example.com<br>
Subject: S/I for example(B/L<br>
No.:4357-0120-810.044) </p>
<p>Please find attached the example.doc), </p>
<p>Thanks. </p>
<p>B.rgds, </p>
<p>xxx xxx </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30<br>
Content-Type: text/html;<br>
charset="us-ascii"<br>
Content-Transfer-Encoding: quoted-printable </p>
<p>
xmlns:o=3D"urn:schemas-microsoft-com:office:office" =<br>
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =<br>
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =<br>
xmlns=3D"<a href="http://www.w3.org/TR/REC-html40" rel="nofollow">http://www.w3.org/TR/REC-html40</a>"> </p>
<p>HTML STUFF till </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30-- </p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30<br>
Content-Type: application/msword;<br>
name="xxxx.doc"<br>
Content-Transfer-Encoding: base64<br>
Content-Disposition: attachment;<br>
filename="xxxx.doc" </p>
<p>0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA
EAAAYgAAAAEAAAD+////AAAAAF8AAAD/////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////s
pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA
AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA
AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE
AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA
AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA
FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA
AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA
AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA</p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30-- </p>
<hr>
<p>I just want to get : </p>
<p>From: xxxx.xxxx [mailto:xxxx@example.com]<br>
Sent: Thursday, October 23, 2008 11:37 AM<br>
To: xxxx@example.com<br>
Subject: S/I for xxxxx (B/L<br>
No.:4357-0120-810.044) </p>
<p>Pls find attached the xxxx.doc), </p>
<p>Thanks. </p>
<p>B.rgds, </p>
<p>xxx xxx </p>
<hr>
<p>not sure if the mail is malformed!
seems if you get an html page you have to do this:</p>
<pre><code> parts=self._currentEmailParsedInstance.get_payload()
print parts[0].get_content_type()
..._multipart/alternative_
textParts=parts[0].get_payload()
print textParts[0].get_content_type()
..._text/plain_
body=textParts[0].get_payload()
print body
...get the text without a problem!!
</code></pre>
<p>thank you so much Vinko.</p>
<p>So its kinda like dealing with xml, recursive in nature.</p>
| 4 | 2008-11-11T07:07:09Z | 280,562 | <p>ended up with this</p>
<pre><code> parser = email.parser.Parser()
self._email = parser.parse(open('/home/vinko/jlm.txt','r'))
parts=self._email.get_payload()
check=parts[0].get_content_type()
if check == "text/plain":
return parts[0].get_payload()
elif check == "multipart/alternative":
part=parts[0].get_payload()
if part[0].get_content_type() == "text/plain":
return part[0].get_payload()
else:
return "cannot obtain the body of the email"
else:
return "cannot obtain the body of the email"
</code></pre>
| 0 | 2008-11-11T10:42:45Z | [
"python",
"email",
"jython",
"parsing"
]
|
Python - sort a list of nested lists | 280,222 | <p>I have input consisting of a list of nested lists like this:</p>
<pre><code>l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:</p>
<pre><code>[39, 6, 13, 50]
</code></pre>
<p>Then I want to sort based on these. So the output should be:</p>
<pre><code>[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>What's a nice pythonic way of doing this?</p>
| 13 | 2008-11-11T07:15:56Z | 280,224 | <pre><code>l.sort(key=sum_nested)
</code></pre>
<p>Where <code>sum_nested()</code> is:</p>
<pre><code>def sum_nested(astruct):
try: return sum(map(sum_nested, astruct))
except TypeError:
return astruct
assert sum_nested([[([8, 9], 10), 11], 12]) == 50
</code></pre>
| 5 | 2008-11-11T07:18:02Z | [
"python",
"list",
"sorting",
"nested-lists"
]
|
Python - sort a list of nested lists | 280,222 | <p>I have input consisting of a list of nested lists like this:</p>
<pre><code>l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:</p>
<pre><code>[39, 6, 13, 50]
</code></pre>
<p>Then I want to sort based on these. So the output should be:</p>
<pre><code>[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>What's a nice pythonic way of doing this?</p>
| 13 | 2008-11-11T07:15:56Z | 280,226 | <p>A little recursive function would do it:</p>
<pre><code>def asum(a):
if isinstance(a, list):
return sum(asum(x) for x in a)
else:
return a
l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
l.sort(key=asum)
print l
</code></pre>
| 12 | 2008-11-11T07:19:20Z | [
"python",
"list",
"sorting",
"nested-lists"
]
|
Python - sort a list of nested lists | 280,222 | <p>I have input consisting of a list of nested lists like this:</p>
<pre><code>l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:</p>
<pre><code>[39, 6, 13, 50]
</code></pre>
<p>Then I want to sort based on these. So the output should be:</p>
<pre><code>[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>What's a nice pythonic way of doing this?</p>
| 13 | 2008-11-11T07:15:56Z | 280,865 | <p>A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:</p>
<pre><code>>>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t
...
>>> sorted(l, key=asum)
[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
</code></pre>
| 15 | 2008-11-11T13:26:37Z | [
"python",
"list",
"sorting",
"nested-lists"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 280,248 | <p>Here's a rather Scheme way to do it:</p>
<pre><code>class cons:
def __init__(self, f, r):
self.__f = f
self.__r = r
def __str__(self):
return "(%s, %s)" % (str(self.__f), str(self.__r))
__repr__ = __str__
class empty:
def __init__(self): pass
__repr__ = lambda self: "empty"
__str__ = __repr__
empty = empty()
def first(self): return self.__f
def rest(self): return self.__r
</code></pre>
<p>I'm looking for a more python way, though, and ideally one that has easier to work with syntax than this:</p>
<pre><code>>>> cons(12, cons(4, cons.empty))
(12, (4, empty))
>>> cons(12, cons(4, cons.empty)).first()
12
>>> cons(12, cons(4, cons.empty)).rest()
(4, empty)
</code></pre>
| 0 | 2008-11-11T07:35:22Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 280,284 | <p>Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function:</p>
<pre><code>def mklist(*args):
result = None
for element in reversed(args):
result = (element, result)
return result
</code></pre>
<p>To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.</p>
| 10 | 2008-11-11T07:54:20Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 280,286 | <p>I wrote this up the other day</p>
<pre><code>#! /usr/bin/env python
class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = node() # create a new node
new_node.data = data
new_node.next = self.cur_node # link the new node to the 'previous' node.
self.cur_node = new_node # set the current node to the new one.
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data
node = node.next
ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.list_print()
</code></pre>
| 35 | 2008-11-11T07:54:49Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 280,572 | <p>When using immutable linked lists, consider using Python's tuple directly. </p>
<pre><code>ls = (1, 2, 3, 4, 5)
def first(ls): return ls[0]
def rest(ls): return ls[1:]
</code></pre>
<p>Its really that ease, and you get to keep the additional funcitons like len(ls), x in ls, etc.</p>
| 0 | 2008-11-11T10:46:43Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 281,294 | <p>Here's a slightly more complex version of a linked list class, with a similar interface to python's sequence types (ie. supports indexing, slicing, concatenation with arbitrary sequences etc). It should have O(1) prepend, doesn't copy data unless it needs to and can be used pretty interchangably with tuples.</p>
<p>It won't be as space or time efficient as lisp cons cells, as python classes are obviously a bit more heavyweight (You could improve things slightly with "<code>__slots__ = '_head','_tail'</code>" to reduce memory usage). It will have the desired big O performance characteristics however.</p>
<p>Example of usage:</p>
<pre><code>>>> l = LinkedList([1,2,3,4])
>>> l
LinkedList([1, 2, 3, 4])
>>> l.head, l.tail
(1, LinkedList([2, 3, 4]))
# Prepending is O(1) and can be done with:
LinkedList.cons(0, l)
LinkedList([0, 1, 2, 3, 4])
# Or prepending arbitrary sequences (Still no copy of l performed):
[-1,0] + l
LinkedList([-1, 0, 1, 2, 3, 4])
# Normal list indexing and slice operations can be performed.
# Again, no copy is made unless needed.
>>> l[1], l[-1], l[2:]
(2, 4, LinkedList([3, 4]))
>>> assert l[2:] is l.next.next
# For cases where the slice stops before the end, or uses a
# non-contiguous range, we do need to create a copy. However
# this should be transparent to the user.
>>> LinkedList(range(100))[-10::2]
LinkedList([90, 92, 94, 96, 98])
</code></pre>
<p>Implementation:</p>
<pre><code>import itertools
class LinkedList(object):
"""Immutable linked list class."""
def __new__(cls, l=[]):
if isinstance(l, LinkedList): return l # Immutable, so no copy needed.
i = iter(l)
try:
head = i.next()
except StopIteration:
return cls.EmptyList # Return empty list singleton.
tail = LinkedList(i)
obj = super(LinkedList, cls).__new__(cls)
obj._head = head
obj._tail = tail
return obj
@classmethod
def cons(cls, head, tail):
ll = cls([head])
if not isinstance(tail, cls):
tail = cls(tail)
ll._tail = tail
return ll
# head and tail are not modifiable
@property
def head(self): return self._head
@property
def tail(self): return self._tail
def __nonzero__(self): return True
def __len__(self):
return sum(1 for _ in self)
def __add__(self, other):
other = LinkedList(other)
if not self: return other # () + l = l
start=l = LinkedList(iter(self)) # Create copy, as we'll mutate
while l:
if not l._tail: # Last element?
l._tail = other
break
l = l._tail
return start
def __radd__(self, other):
return LinkedList(other) + self
def __iter__(self):
x=self
while x:
yield x.head
x=x.tail
def __getitem__(self, idx):
"""Get item at specified index"""
if isinstance(idx, slice):
# Special case: Avoid constructing a new list, or performing O(n) length
# calculation for slices like l[3:]. Since we're immutable, just return
# the appropriate node. This becomes O(start) rather than O(n).
# We can't do this for more complicated slices however (eg [l:4]
start = idx.start or 0
if (start >= 0) and (idx.stop is None) and (idx.step is None or idx.step == 1):
no_copy_needed=True
else:
length = len(self) # Need to calc length.
start, stop, step = idx.indices(length)
no_copy_needed = (stop == length) and (step == 1)
if no_copy_needed:
l = self
for i in range(start):
if not l: break # End of list.
l=l.tail
return l
else:
# We need to construct a new list.
if step < 1: # Need to instantiate list to deal with -ve step
return LinkedList(list(self)[start:stop:step])
else:
return LinkedList(itertools.islice(iter(self), start, stop, step))
else:
# Non-slice index.
if idx < 0: idx = len(self)+idx
if not self: raise IndexError("list index out of range")
if idx == 0: return self.head
return self.tail[idx-1]
def __mul__(self, n):
if n <= 0: return Nil
l=self
for i in range(n-1): l += self
return l
def __rmul__(self, n): return self * n
# Ideally we should compute the has ourselves rather than construct
# a temporary tuple as below. I haven't impemented this here
def __hash__(self): return hash(tuple(self))
def __eq__(self, other): return self._cmp(other) == 0
def __ne__(self, other): return not self == other
def __lt__(self, other): return self._cmp(other) < 0
def __gt__(self, other): return self._cmp(other) > 0
def __le__(self, other): return self._cmp(other) <= 0
def __ge__(self, other): return self._cmp(other) >= 0
def _cmp(self, other):
"""Acts as cmp(): -1 for self<other, 0 for equal, 1 for greater"""
if not isinstance(other, LinkedList):
return cmp(LinkedList,type(other)) # Arbitrary ordering.
A, B = iter(self), iter(other)
for a,b in itertools.izip(A,B):
if a<b: return -1
elif a > b: return 1
try:
A.next()
return 1 # a has more items.
except StopIteration: pass
try:
B.next()
return -1 # b has more items.
except StopIteration: pass
return 0 # Lists are equal
def __repr__(self):
return "LinkedList([%s])" % ', '.join(map(repr,self))
class EmptyList(LinkedList):
"""A singleton representing an empty list."""
def __new__(cls):
return object.__new__(cls)
def __iter__(self): return iter([])
def __nonzero__(self): return False
@property
def head(self): raise IndexError("End of list")
@property
def tail(self): raise IndexError("End of list")
# Create EmptyList singleton
LinkedList.EmptyList = EmptyList()
del EmptyList
</code></pre>
| 11 | 2008-11-11T15:59:46Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 282,238 | <p>For some needs, a <a href="https://docs.python.org/library/collections.html#collections.deque">deque</a> may also be useful. You can add and remove items on both ends of a deque at O(1) cost.</p>
<pre><code>from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
</code></pre>
| 112 | 2008-11-11T21:45:30Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 283,630 | <p>Here is some list functions based on <a href="http://stackoverflow.com/questions/280243/python-linked-list#280284">Martin v. Löwis's representation</a>:</p>
<pre><code>cons = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")
</code></pre>
<p>where <code>w = sys.stdout.write</code></p>
<p>Linked lists have no practical value in Python.
I've <em>never</em> used a linked list in Python for any problem except educational.</p>
<p>Thomas Watnedal <a href="http://stackoverflow.com/questions/280243/python-linked-list#280280">suggested</a> a good educational resource <a href="http://greenteapress.com/thinkpython/html/chap17.html">How to Think Like a Computer Scientist, Chapter 17: Linked lists</a>:</p>
<p>A linked list is either: </p>
<ul>
<li>the empty list, represented by None, or </li>
<li><p>a node that contains a cargo object and a reference to a linked list.</p>
<pre><code>class Node:
def __init__(self, cargo=None, next=None):
self.car = cargo
self.cdr = next
def __str__(self):
return str(self.car)
def display(lst):
if lst:
w("%s " % lst)
display(lst.cdr)
else:
w("nil\n")
</code></pre></li>
</ul>
| 51 | 2008-11-12T11:10:15Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 3,538,133 | <p>The accepted answer is rather complicated. Here is a more standard design:</p>
<pre><code>L = LinkedList()
L.insert(1)
L.insert(1)
L.insert(2)
L.insert(4)
print L
L.clear()
print L
</code></pre>
<p>It is a simple <code>LinkedList</code> class based on the straightforward C++ design and <a href="http://greenteapress.com/thinkpython/html/chap17.html">Chapter 17: Linked lists</a>, as recommended by <a href="http://stackoverflow.com/questions/280243/python-linked-list/280280#280280">Thomas Watnedal</a>.</p>
<pre><code>class Node:
def __init__(self, value = None, next = None):
self.value = value
self.next = next
def __str__(self):
return 'Node ['+str(self.value)+']'
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def insert(self, x):
if self.first == None:
self.first = Node(x, None)
self.last = self.first
elif self.last == self.first:
self.last = Node(x, None)
self.first.next = self.last
else:
current = Node(x, None)
self.last.next = current
self.last = current
def __str__(self):
if self.first != None:
current = self.first
out = 'LinkedList [\n' +str(current.value) +'\n'
while current.next != None:
current = current.next
out += str(current.value) + '\n'
return out + ']'
return 'LinkedList []'
def clear(self):
self.__init__()
</code></pre>
| 13 | 2010-08-21T16:04:51Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 6,658,636 | <p>I based this additional function on <a href="http://stackoverflow.com/users/4960/nick-stinemates">Nick Stinemates</a></p>
<pre><code>def add_node_at_end(self, data):
new_node = Node()
node = self.curr_node
while node:
if node.next == None:
node.next = new_node
new_node.next = None
new_node.data = data
node = node.next
</code></pre>
<p>The method he has adds the new node at the beginning while I have seen a lot of implementations which usually add a new node at the end but whatever, it is fun to do.</p>
| 1 | 2011-07-12T01:37:41Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 8,367,288 | <p>I think the implementation below fill the bill quite gracefully.</p>
<pre><code>'''singly linked lists, by Yingjie Lan, December 1st, 2011'''
class linkst:
'''Singly linked list, with pythonic features.
The list has pointers to both the first and the last node.'''
__slots__ = ['data', 'next'] #memory efficient
def __init__(self, iterable=(), data=None, next=None):
'''Provide an iterable to make a singly linked list.
Set iterable to None to make a data node for internal use.'''
if iterable is not None:
self.data, self.next = self, None
self.extend(iterable)
else: #a common node
self.data, self.next = data, next
def empty(self):
'''test if the list is empty'''
return self.next is None
def append(self, data):
'''append to the end of list.'''
last = self.data
self.data = last.next = linkst(None, data)
#self.data = last.next
def insert(self, data, index=0):
'''insert data before index.
Raise IndexError if index is out of range'''
curr, cat = self, 0
while cat < index and curr:
curr, cat = curr.next, cat+1
if index<0 or not curr:
raise IndexError(index)
new = linkst(None, data, curr.next)
if curr.next is None: self.data = new
curr.next = new
def reverse(self):
'''reverse the order of list in place'''
current, prev = self.next, None
while current: #what if list is empty?
next = current.next
current.next = prev
prev, current = current, next
if self.next: self.data = self.next
self.next = prev
def delete(self, index=0):
'''remvoe the item at index from the list'''
curr, cat = self, 0
while cat < index and curr.next:
curr, cat = curr.next, cat+1
if index<0 or not curr.next:
raise IndexError(index)
curr.next = curr.next.next
if curr.next is None: #tail
self.data = curr #current == self?
def remove(self, data):
'''remove first occurrence of data.
Raises ValueError if the data is not present.'''
current = self
while current.next: #node to be examined
if data == current.next.data: break
current = current.next #move on
else: raise ValueError(data)
current.next = current.next.next
if current.next is None: #tail
self.data = current #current == self?
def __contains__(self, data):
'''membership test using keyword 'in'.'''
current = self.next
while current:
if data == current.data:
return True
current = current.next
return False
def __iter__(self):
'''iterate through list by for-statements.
return an iterator that must define the __next__ method.'''
itr = linkst()
itr.next = self.next
return itr #invariance: itr.data == itr
def __next__(self):
'''the for-statement depends on this method
to provide items one by one in the list.
return the next data, and move on.'''
#the invariance is checked so that a linked list
#will not be mistakenly iterated over
if self.data is not self or self.next is None:
raise StopIteration()
next = self.next
self.next = next.next
return next.data
def __repr__(self):
'''string representation of the list'''
return 'linkst(%r)'%list(self)
def __str__(self):
'''converting the list to a string'''
return '->'.join(str(i) for i in self)
#note: this is NOT the class lab! see file linked.py.
def extend(self, iterable):
'''takes an iterable, and append all items in the iterable
to the end of the list self.'''
last = self.data
for i in iterable:
last.next = linkst(None, i)
last = last.next
self.data = last
def index(self, data):
'''TODO: return first index of data in the list self.
Raises ValueError if the value is not present.'''
#must not convert self to a tuple or any other containers
current, idx = self.next, 0
while current:
if current.data == data: return idx
current, idx = current.next, idx+1
raise ValueError(data)
</code></pre>
| 0 | 2011-12-03T11:20:54Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 15,182,629 | <p>The following is what I came up with. It's similer to <a href="http://stackoverflow.com/a/280286/176611">Riccardo C.'s</a>, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.</p>
<pre><code>class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
self.curr = None
self.tail = None
def __iter__(self):
return self
def next(self):
if self.head and not self.curr:
self.curr = self.head
return self.curr
elif self.curr.next:
self.curr = self.curr.next
return self.curr
else:
raise StopIteration
def append(self, data):
n = Node(data)
if not self.head:
self.head = n
self.tail = n
else:
self.tail.next = n
self.tail = self.tail.next
# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
ll.append(i)
# print out the list
for n in ll:
print n
"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""
</code></pre>
| 1 | 2013-03-03T05:03:45Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 17,850,004 | <pre><code>class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def insert(self, node):
if not self.next:
self.next = node
else:
self.next.insert(node)
def __str__(self):
if self.next:
return '%s -> %s' % (self.value, str(self.next))
else:
return ' %s ' % self.value
if __name__ == "__main__":
items = ['a', 'b', 'c', 'd', 'e']
ll = None
for item in items:
if ll:
next_ll = LinkedList(item)
ll.insert(next_ll)
else:
ll = LinkedList(item)
print('[ %s ]' % ll)
</code></pre>
| 0 | 2013-07-25T05:49:11Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 19,008,675 | <p>I just did <a href="https://github.com/tlevine/cons.py/blob/master/cons.py" rel="nofollow">this</a> as a fun toy. It should be immutable as long as you don't touch the underscore-prefixed methods, and it implements a bunch of Python magic like indexing and <code>len</code>.</p>
| 1 | 2013-09-25T15:11:25Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 20,658,095 | <p>First of all, I assume you want linked lists. In practice, you can use <code>collections.deque</code>, whose current CPython implementation is a doubly linked list of blocks (each block contains an array of 62 cargo objects). It subsumes linked list's functionality. You can also search for a C extension called <code>llist</code> on pypi. If you want a pure-Python and easy-to-follow implementation of the linked list ADT, you can take a look at my following minimal implementation.</p>
<pre><code>class Node (object):
""" Node for a linked list. """
def __init__ (self, value, next=None):
self.value = value
self.next = next
class LinkedList (object):
""" Linked list ADT implementation using class.
A linked list is a wrapper of a head pointer
that references either None, or a node that contains
a reference to a linked list.
"""
def __init__ (self, iterable=()):
self.head = None
for x in iterable:
self.head = Node(x, self.head)
def __iter__ (self):
p = self.head
while p is not None:
yield p.value
p = p.next
def prepend (self, x): # 'appendleft'
self.head = Node(x, self.head)
def reverse (self):
""" In-place reversal. """
p = self.head
self.head = None
while p is not None:
p0, p = p, p.next
p0.next = self.head
self.head = p0
if __name__ == '__main__':
ll = LinkedList([6,5,4])
ll.prepend(3); ll.prepend(2)
print list(ll)
ll.reverse()
print list(ll)
</code></pre>
| 0 | 2013-12-18T12:21:55Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 24,342,598 | <pre><code>class LL(object):
def __init__(self,val):
self.val = val
self.next = None
def pushNodeEnd(self,top,val):
if top is None:
top.val=val
top.next=None
else:
tmp=top
while (tmp.next != None):
tmp=tmp.next
newNode=LL(val)
newNode.next=None
tmp.next=newNode
def pushNodeFront(self,top,val):
if top is None:
top.val=val
top.next=None
else:
newNode=LL(val)
newNode.next=top
top=newNode
def popNodeFront(self,top):
if top is None:
return
else:
sav=top
top=top.next
return sav
def popNodeEnd(self,top):
if top is None:
return
else:
tmp=top
while (tmp.next != None):
prev=tmp
tmp=tmp.next
prev.next=None
return tmp
top=LL(10)
top.pushNodeEnd(top, 20)
top.pushNodeEnd(top, 30)
pop=top.popNodeEnd(top)
print (pop.val)
</code></pre>
| 0 | 2014-06-21T14:32:51Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 24,987,486 | <p>I've put a Python 2.x and 3.x singly-linked list class at <a href="https://pypi.python.org/pypi/linked_list_mod/" rel="nofollow">https://pypi.python.org/pypi/linked_list_mod/</a></p>
<p>It's tested with CPython 2.7, CPython 3.4, Pypy 2.3.1, Pypy3 2.3.1, and Jython 2.7b2, and comes with a nice automated test suite.</p>
<p>It also includes LIFO and FIFO classes.</p>
<p>They aren't immutable though.</p>
| 0 | 2014-07-28T01:48:23Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 26,088,052 | <p>My 2 cents </p>
<pre><code>class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.first = None
self.last = None
def add(self, x):
current = Node(x, None)
try:
self.last.next = current
except AttributeError:
self.first = current
self.last = current
else:
self.last = current
def print_list(self):
node = self.first
while node:
print node.value
node = node.next
ll = LinkedList()
ll.add("1st")
ll.add("2nd")
ll.add("3rd")
ll.add("4th")
ll.add("5th")
ll.print_list()
# Result:
# 1st
# 2nd
# 3rd
# 4th
# 5th
</code></pre>
| 0 | 2014-09-28T18:20:00Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 26,658,719 | <pre><code>enter code here
enter code here
class node:
def __init__(self):
self.data = None
self.next = None
class linked_list:
def __init__(self):
self.cur_node = None
self.head = None
def add_node(self,data):
new_node = node()
if self.head == None:
self.head = new_node
self.cur_node = new_node
new_node.data = data
new_node.next = None
self.cur_node.next = new_node
self.cur_node = new_node
def list_print(self):
node = self.head
while node:
print (node.data)
node = node.next
def delete(self):
node = self.head
next_node = node.next
del(node)
self.head = next_node
a = linked_list()
a.add_node(1)
a.add_node(2)
a.add_node(3)
a.add_node(4)
a.delete()
a.list_print()
</code></pre>
| 0 | 2014-10-30T16:45:52Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 26,671,637 | <p>If you want to just create a simple liked list then refer this code</p>
<p>l=[1,[2,[3,[4,[5,[6,[7,[8,[9,[10]]]]]]]]]]</p>
<p>for visualize execution for this cod Visit <a href="http://www.pythontutor.com/visualize.html#mode=edit" rel="nofollow">http://www.pythontutor.com/visualize.html#mode=edit</a> </p>
| 0 | 2014-10-31T09:47:20Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 29,676,547 | <p>The code given by user201788, intended to change Prepend in Nick Stinemates's original code to Append, doesn't work. Because self.cur_node is not updated, it stays as None, so the while loop will never happen. To make it work, we just need to do one more thing, change the initialization of class linked_list.</p>
<pre><code>class linked_list:
def __init__(self):
#self.cur_node = None # Nick Stinemate's code
self.cur_node = node() # in order to "append"
</code></pre>
| 0 | 2015-04-16T13:40:36Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 39,681,493 | <p>I envision a dictionary as a linked list.</p>
<p>Say we have a list of cat -> dog -> rat -> bat:</p>
<pre><code>dict1 = {}
dict1["root"] = "cat"
dict1["cat"] = "dog"
dict1["dog"] = "rat"
dict1["rat"] = "bat"
dict1["bat"] = None
</code></pre>
<p>Insertion: </p>
<pre><code>dict1["peacock"] = dict1["dog"]
dict1["dog"] = "peacock"
</code></pre>
<p>Is there any problem with this approach in terms of time and space complexity?</p>
| 0 | 2016-09-24T22:23:56Z | [
"python",
"linked-list"
]
|
Python Linked List | 280,243 | <p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
| 110 | 2008-11-11T07:31:21Z | 40,072,598 | <pre><code>class LinkedStack:
'''LIFO Stack implementation using a singly linked list for storage.'''
_ToList = []
#---------- nested _Node class -----------------------------
class _Node:
'''Lightweight, nonpublic class for storing a singly linked node.'''
__slots__ = '_element', '_next' #streamline memory usage
def __init__(self, element, next):
self._element = element
self._next = next
#--------------- stack methods ---------------------------------
def __init__(self):
'''Create an empty stack.'''
self._head = None
self._size = 0
def __len__(self):
'''Return the number of elements in the stack.'''
return self._size
def IsEmpty(self):
'''Return True if the stack is empty'''
return self._size == 0
def Push(self,e):
'''Add element e to the top of the Stack.'''
self._head = self._Node(e, self._head) #create and link a new node
self._size +=1
self._ToList.append(e)
def Top(self):
'''Return (but do not remove) the element at the top of the stack.
Raise exception if the stack is empty
'''
if self.IsEmpty():
raise Exception('Stack is empty')
return self._head._element #top of stack is at head of list
def Pop(self):
'''Remove and return the element from the top of the stack (i.e. LIFO).
Raise exception if the stack is empty
'''
if self.IsEmpty():
raise Exception('Stack is empty')
answer = self._head._element
self._head = self._head._next #bypass the former top node
self._size -=1
self._ToList.remove(answer)
return answer
def Count(self):
'''Return how many nodes the stack has'''
return self.__len__()
def Clear(self):
'''Delete all nodes'''
for i in range(self.Count()):
self.Pop()
def ToList(self):
return self._ToList
</code></pre>
| 0 | 2016-10-16T16:30:52Z | [
"python",
"linked-list"
]
|
When is "self" required? | 280,324 | <p>I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.</p>
<p>However, I'm looking through the <em>wxPython in Action</em> book and notice that "self" isn't used all the time. For example:</p>
<pre><code> import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
</code></pre>
<p>The one below does use "self".</p>
<pre><code>import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
</code></pre>
<p>If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?</p>
| 9 | 2008-11-11T08:24:00Z | 280,332 | <p>In those instances, if you do not use <code>self</code> then you will create only a local variable of that name. In the first example, <code>panel</code> is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing <code>self</code> to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns.</p>
| 4 | 2008-11-11T08:26:41Z | [
"python",
"wxpython"
]
|
When is "self" required? | 280,324 | <p>I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.</p>
<p>However, I'm looking through the <em>wxPython in Action</em> book and notice that "self" isn't used all the time. For example:</p>
<pre><code> import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
</code></pre>
<p>The one below does use "self".</p>
<pre><code>import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
</code></pre>
<p>If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?</p>
| 9 | 2008-11-11T08:24:00Z | 280,336 | <p>self is <strong>always</strong> required when referring to the instance itself, except when calling the base class constructor (wx.Frame.__init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all. These names will be gone when the method returns - everything put into self.foo will survive the end of the method, and be available in the next method (e.g. self.button).</p>
| 0 | 2008-11-11T08:27:44Z | [
"python",
"wxpython"
]
|
When is "self" required? | 280,324 | <p>I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.</p>
<p>However, I'm looking through the <em>wxPython in Action</em> book and notice that "self" isn't used all the time. For example:</p>
<pre><code> import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
</code></pre>
<p>The one below does use "self".</p>
<pre><code>import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
</code></pre>
<p>If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?</p>
| 9 | 2008-11-11T08:24:00Z | 280,561 | <p>You use <code>self.attribute</code> to reference an attribute of your current instance.</p>
<p>You use <code>wx.Frame.__init__()</code> to reference a method of the parent class.</p>
<p>You don't use <code>self</code> if you only reference a local name (variable) of the method (function) you are in.</p>
<p>These are not "rules of thumb," because there are no exceptions.</p>
<p><hr /></p>
<p>What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.</p>
<p>If you look at the documentation to <code>wx.Panel</code>, though, you will see that <em>its</em> constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.</p>
<p>Magic :)</p>
| 7 | 2008-11-11T10:42:20Z | [
"python",
"wxpython"
]
|
Escaping regex string in Python | 280,435 | <p>I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex? For example, the user wants to search for Word <code>(s)</code>: regex engine will take the <code>(s)</code> as a group. I want it to treat it like a string <code>"(s)" </code>. I can run <code>replace</code> on user input and replace the <code>(</code> with <code>\(</code> and the <code>)</code> with <code>\)</code> but the problem is I will need to do replace for every possible regex symbol. Do you know some better way ?</p>
| 128 | 2008-11-11T09:33:29Z | 280,441 | <p>Use the <code>re.escape()</code> function for this:</p>
<p><a href="http://docs.python.org/library/re.html#re.escape">4.2.3 <code>re</code> Module Contents</a></p>
<blockquote>
<p><strong>escape(string)</strong></p>
<p>Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.</p>
</blockquote>
<p>A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.</p>
<pre><code>def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
</code></pre>
| 174 | 2008-11-11T09:37:37Z | [
"python",
"regex"
]
|
Escaping regex string in Python | 280,435 | <p>I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex? For example, the user wants to search for Word <code>(s)</code>: regex engine will take the <code>(s)</code> as a group. I want it to treat it like a string <code>"(s)" </code>. I can run <code>replace</code> on user input and replace the <code>(</code> with <code>\(</code> and the <code>)</code> with <code>\)</code> but the problem is I will need to do replace for every possible regex symbol. Do you know some better way ?</p>
| 128 | 2008-11-11T09:33:29Z | 280,463 | <p>You can use <a href="http://docs.python.org/library/re.html#re.escape">re.escape()</a>: </p>
<blockquote>
<p>re.escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.</p>
</blockquote>
<pre><code>>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
</code></pre>
| 33 | 2008-11-11T09:49:25Z | [
"python",
"regex"
]
|
Calculate poisson probability percentage | 280,797 | <p>When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:</p>
<ul>
<li>an integer</li>
<li>an 'average' number</li>
</ul>
<p>and returns a float.</p>
<p>In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).</p>
<p>for example:</p>
<pre><code>print poisson(2.6,6)
</code></pre>
<p>returns <code>[1 3 3 0 1 3]</code> (and every time I run it, it's different).</p>
<p>The number I get from calc/excel is 3.19 (<code>POISSON(6,2.16,0)*100</code>).</p>
<p>Am I using the python's poisson wrong (no pun!) or am I missing something?</p>
| 16 | 2008-11-11T12:51:43Z | 280,831 | <p><a href="http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm#pgfId-305426" rel="nofollow">This page</a> explains why you get an array, and the meaning of the numbers in it, at least.</p>
| 1 | 2008-11-11T13:12:40Z | [
"python",
"statistics",
"poisson"
]
|
Calculate poisson probability percentage | 280,797 | <p>When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:</p>
<ul>
<li>an integer</li>
<li>an 'average' number</li>
</ul>
<p>and returns a float.</p>
<p>In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).</p>
<p>for example:</p>
<pre><code>print poisson(2.6,6)
</code></pre>
<p>returns <code>[1 3 3 0 1 3]</code> (and every time I run it, it's different).</p>
<p>The number I get from calc/excel is 3.19 (<code>POISSON(6,2.16,0)*100</code>).</p>
<p>Am I using the python's poisson wrong (no pun!) or am I missing something?</p>
| 16 | 2008-11-11T12:51:43Z | 280,843 | <p><code>scipy</code> has what you want</p>
<pre><code>>>> scipy.stats.distributions
<module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'>
>>> scipy.stats.distributions.poisson.pmf(6, 2.6)
array(0.031867055625524499)
</code></pre>
<p>It's worth noting that it's pretty easy to calculate by hand, <a href="http://www.scipy.org/doc/api_docs/SciPy.stats.distributions.html#poisson">too</a>.</p>
| 20 | 2008-11-11T13:17:55Z | [
"python",
"statistics",
"poisson"
]
|
Calculate poisson probability percentage | 280,797 | <p>When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:</p>
<ul>
<li>an integer</li>
<li>an 'average' number</li>
</ul>
<p>and returns a float.</p>
<p>In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).</p>
<p>for example:</p>
<pre><code>print poisson(2.6,6)
</code></pre>
<p>returns <code>[1 3 3 0 1 3]</code> (and every time I run it, it's different).</p>
<p>The number I get from calc/excel is 3.19 (<code>POISSON(6,2.16,0)*100</code>).</p>
<p>Am I using the python's poisson wrong (no pun!) or am I missing something?</p>
| 16 | 2008-11-11T12:51:43Z | 280,862 | <p>It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow:</p>
<pre><code>def poisson_probability(actual, mean):
# naive: math.exp(-mean) * mean**actual / factorial(actual)
# iterative, to keep the components from getting too large or small:
p = math.exp(-mean)
for i in xrange(actual):
p *= mean
p /= i+1
return p
</code></pre>
| 12 | 2008-11-11T13:24:40Z | [
"python",
"statistics",
"poisson"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 281,330 | <p>I dug through the source code of Synergy to find the call that generates mouse events:</p>
<pre><code>#include <ApplicationServices/ApplicationServices.h>
int to(int x, int y)
{
CGPoint newloc;
CGEventRef eventRef;
newloc.x = x;
newloc.y = y;
eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
kCGMouseButtonCenter);
//Apparently, a bug in xcode requires this next line
CGEventSetType(eventRef, kCGEventMouseMoved);
CGEventPost(kCGSessionEventTap, eventRef);
CFRelease(eventRef);
return 0;
}
</code></pre>
<p>Now to write Python bindings!</p>
| 7 | 2008-11-11T16:10:11Z | [
"python",
"osx",
"mouse"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 281,366 | <p>When I wanted to do it, I installed <a href="http://www.jython.org/Project/" rel="nofollow">Jython</a> and used the <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html" rel="nofollow"><code>java.awt.Robot</code></a> class. If you need to make a CPython script this is obviously not suitable, but when you the flexibility to choose anything it is a nice cross-platform solution.</p>
<pre><code>import java.awt
robot = java.awt.Robot()
robot.mouseMove(x, y)
robot.mousePress(java.awt.event.InputEvent.BUTTON1_MASK)
robot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK)
</code></pre>
| 8 | 2008-11-11T16:23:20Z | [
"python",
"osx",
"mouse"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 292,117 | <p>The easiest way? Compile <a href="http://www.macosxhints.com/article.php?story=2008051406323031" rel="nofollow">this</a> Cocoa app and pass it your mouse movements.</p>
<p>Another way? Import <a href="http://developer.apple.com/cocoa/pyobjc.html" rel="nofollow">pyobjc</a> to access some of the OSX framework and access the mouse that way. (see the code from the first example for ideas).</p>
| 0 | 2008-11-15T03:48:07Z | [
"python",
"osx",
"mouse"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 664,417 | <p>Just try this code:</p>
<pre><code>#!/usr/bin/python
import objc
class ETMouse():
def setMousePosition(self, x, y):
bndl = objc.loadBundle('CoreGraphics', globals(),
'/System/Library/Frameworks/ApplicationServices.framework')
objc.loadBundleFunctions(bndl, globals(),
[('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
CGWarpMouseCursorPosition((x, y))
if __name__ == "__main__":
et = ETMouse()
et.setMousePosition(200, 200)
</code></pre>
<p>it works in OSX leopard 10.5.6</p>
| 9 | 2009-03-19T23:15:07Z | [
"python",
"osx",
"mouse"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 8,202,674 | <p>Try the code at <a href="http://www.geekorgy.com/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/">http://www.geekorgy.com/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/</a>, pasted below in case the site disappears.</p>
<p>It defines a couple of functions, mousemove and mouseclick, which hook into Apple's integration between Python and the platform's Quartz libraries.</p>
<p>This code works on 10.6, and I'm using it on 10.7. The nice thing about this code is that it generates mouse events, which some solutions don't. I use it to control BBC iPlayer by sending mouse events to known button positions in their Flash player (very brittle I know). The mouse move events, in particular, are required as otherwise the Flash player never hides the mouse cursor. Functions like CGWarpMouseCursorPosition will not do this.</p>
<pre><code>from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseUp
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGHIDEventTap
def mouseEvent(type, posx, posy):
theEvent = CGEventCreateMouseEvent(
None,
type,
(posx,posy),
kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)
def mousemove(posx,posy):
mouseEvent(kCGEventMouseMoved, posx,posy);
def mouseclick(posx,posy):
# uncomment this line if you want to force the mouse
# to MOVE to the click location first (I found it was not necessary).
#mouseEvent(kCGEventMouseMoved, posx,posy);
mouseEvent(kCGEventLeftMouseDown, posx,posy);
mouseEvent(kCGEventLeftMouseUp, posx,posy);
</code></pre>
| 19 | 2011-11-20T15:48:30Z | [
"python",
"osx",
"mouse"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 10,696,392 | <p>The python script from <a href="http://www.geekorgy.com/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/" rel="nofollow">geekorgy.com</a> is great except I ran into a few snags since I installed a newer version of python. So here are some tips to others who may be looking for a solution.</p>
<p>If you installed Python 2.7 on your Mac OS 10.6 you have a few options to get python to import from Quartz.CoreGraphics:</p>
<p><strong>A)</strong> In the terminal, <strong>type <code>python2.6</code></strong> instead of just <code>python</code> before the path to the script</p>
<p><strong>B)</strong> You can <strong>install PyObjC</strong> by doing the following:</p>
<ol>
<li>Install easy_install from <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">http://pypi.python.org/pypi/setuptools</a></li>
<li>In the terminal, type <code>which python</code> and copy the path up through <code>2.7</code></li>
<li><p>Then type <code>easy_install â-prefix /Path/To/Python/Version pyobjc==2.3</code> </p>
<p>**ie. <code>easy_install â-prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc==2.3</code></p></li>
<li>Inside the script type <code>import objc</code> at the top</li>
<li><p>If easy_install doesn't work the first time you might need to install the core first:</p>
<p>**ie. <code>easy_install --prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc-core==2.3</code></p></li>
</ol>
<p><strong>C)</strong> You can <strong>reset your python path</strong> to the original Mac OS python:</p>
<ul>
<li>In the terminal, type: <code>defaults write com.apple.versioner.python Version 2.6</code></li>
</ul>
<p>***Also, a quick way to find out the (x,y) coordinates on the screen:</p>
<ol>
<li>Press <code>Command+Shift+4</code> (screen grab selection)</li>
<li>The cursor then shows the coordinates</li>
<li>Then hit Esc to get out of it.</li>
</ol>
| 1 | 2012-05-22T05:51:10Z | [
"python",
"osx",
"mouse"
]
|
Controlling the mouse from Python in OS X | 281,133 | <p>What would be the easiest way to move the mouse around (and possibly click) using python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
<p>Thanks!</p>
| 19 | 2008-11-11T15:04:43Z | 17,578,617 | <p>Your best bet is to use the <a href="https://pypi.python.org/pypi/autopy/0.51" rel="nofollow">AutoPy package</a>. It's extremely simple to use, and cross-platform to boot.</p>
<p>To move the cursor to position (200,200):</p>
<pre><code>import autopy
autopy.mouse.move(200,200)
</code></pre>
| 1 | 2013-07-10T18:49:19Z | [
"python",
"osx",
"mouse"
]
|
Open explorer on a file | 281,888 | <p>In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:</p>
<pre><code>import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')
</code></pre>
<p>but I have no solution for files.</p>
| 30 | 2008-11-11T19:24:56Z | 281,911 | <p>From <a href="http://support.microsoft.com/kb/314853">Explorer.exe Command-Line Options for Windows XP</a></p>
<pre><code>import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
</code></pre>
| 33 | 2008-11-11T19:33:14Z | [
"python",
"windows",
"explorer"
]
|
Open explorer on a file | 281,888 | <p>In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:</p>
<pre><code>import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')
</code></pre>
<p>but I have no solution for files.</p>
| 30 | 2008-11-11T19:24:56Z | 27,251,095 | <p>For some reason, on windows 7 it always opens the users Path, for me following worked out:</p>
<pre><code>import subprocess
subprocess.call("explorer C:\\temp\\yourpath", shell=True)
</code></pre>
| 4 | 2014-12-02T13:51:51Z | [
"python",
"windows",
"explorer"
]
|
How can I do synchronous rpc calls | 281,922 | <p>I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.</p>
<pre><code>c = ClientCreator(reactor, Greeter)
c.connectTCP(self.host, self.port).addCallback(request)
reactor.run()
</code></pre>
<p>This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?</p>
<p>(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)</p>
<p>Addendum & Clarification:</p>
<p>I shared a google doc with notes on what I'm doing. <a href="http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz" rel="nofollow">http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz</a></p>
<p>I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<a href="http://pyro.sourceforge.net/" rel="nofollow">http://pyro.sourceforge.net/</a>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.</p>
<p>I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.</p>
<p><strong>Conclusion:</strong>
I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<a href="http://launchpad.net/dstorage" rel="nofollow">http://launchpad.net/dstorage</a>).</p>
| 4 | 2008-11-11T19:38:34Z | 281,991 | <p>For a synchronous client, Twisted probably isn't the right option. Instead, you might want to use the socket module directly.</p>
<pre><code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.send(output)
data = s.recv(size)
s.close()
</code></pre>
<p>The <code>recv()</code> call might need to be repeated until you get an empty string, but this shows the basics.</p>
<p>Alternatively, you can rearrange your entire program to support asynchronous calls...</p>
| 1 | 2008-11-11T20:04:35Z | [
"python",
"twisted"
]
|
How can I do synchronous rpc calls | 281,922 | <p>I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.</p>
<pre><code>c = ClientCreator(reactor, Greeter)
c.connectTCP(self.host, self.port).addCallback(request)
reactor.run()
</code></pre>
<p>This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?</p>
<p>(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)</p>
<p>Addendum & Clarification:</p>
<p>I shared a google doc with notes on what I'm doing. <a href="http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz" rel="nofollow">http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz</a></p>
<p>I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<a href="http://pyro.sourceforge.net/" rel="nofollow">http://pyro.sourceforge.net/</a>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.</p>
<p>I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.</p>
<p><strong>Conclusion:</strong>
I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<a href="http://launchpad.net/dstorage" rel="nofollow">http://launchpad.net/dstorage</a>).</p>
| 4 | 2008-11-11T19:38:34Z | 282,301 | <p>If you are using Twisted you should probably know that:</p>
<ol>
<li>You will not be making synchronous calls to any network service</li>
<li>The reactor can only ever be run once, so do not stop it (by calling <code>reactor.stop()</code>) until your application is ready to exit.</li>
</ol>
<p>I hope this answers your question. I personally believe that Twisted is <strong>exactly</strong> the correct solution for your use case, but that you need to work around your synchronicity issue.</p>
<p>Addendum & Clarification:</p>
<blockquote>
<p>Part of what I don't understand is
that when I call reactor.run() it
seems to go into a loop that just
watches for network activity. How do I
continue running the rest of my
program while it uses the network? if
I can get past that, then I can
probably work through the
synchronicity issue.</p>
</blockquote>
<p>That is exactly what reactor.run() does. It runs a main loop which is an event reactor. It will not only wait for entwork events, but anything else you have scheduled to happen. With Twisted you will need to structure the rest of your application in a way to deal with its asynchronous nature. Perhaps if we knew what kind of application it is, we could advise.</p>
| 1 | 2008-11-11T22:07:13Z | [
"python",
"twisted"
]
|
How can I do synchronous rpc calls | 281,922 | <p>I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.</p>
<pre><code>c = ClientCreator(reactor, Greeter)
c.connectTCP(self.host, self.port).addCallback(request)
reactor.run()
</code></pre>
<p>This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?</p>
<p>(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)</p>
<p>Addendum & Clarification:</p>
<p>I shared a google doc with notes on what I'm doing. <a href="http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz" rel="nofollow">http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz</a></p>
<p>I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<a href="http://pyro.sourceforge.net/" rel="nofollow">http://pyro.sourceforge.net/</a>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.</p>
<p>I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.</p>
<p><strong>Conclusion:</strong>
I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<a href="http://launchpad.net/dstorage" rel="nofollow">http://launchpad.net/dstorage</a>).</p>
| 4 | 2008-11-11T19:38:34Z | 288,650 | <p>If you're even considering Pyro, check out <a href="http://rpyc.wikidot.com/" rel="nofollow">RPyC</a> first, and re-consider XML-RPC.</p>
<p>Regarding Twisted: try leaving the reactor up instead of stopping it, and just <code>ClientCreator(...).connectTCP(...)</code> each time.</p>
<p>If you <code>self.transport.loseConnection()</code> in your Protocol you won't be leaving open connections.</p>
| 2 | 2008-11-13T22:53:32Z | [
"python",
"twisted"
]
|
How can I do synchronous rpc calls | 281,922 | <p>I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.</p>
<pre><code>c = ClientCreator(reactor, Greeter)
c.connectTCP(self.host, self.port).addCallback(request)
reactor.run()
</code></pre>
<p>This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?</p>
<p>(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)</p>
<p>Addendum & Clarification:</p>
<p>I shared a google doc with notes on what I'm doing. <a href="http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz" rel="nofollow">http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz</a></p>
<p>I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<a href="http://pyro.sourceforge.net/" rel="nofollow">http://pyro.sourceforge.net/</a>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.</p>
<p>I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.</p>
<p><strong>Conclusion:</strong>
I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<a href="http://launchpad.net/dstorage" rel="nofollow">http://launchpad.net/dstorage</a>).</p>
| 4 | 2008-11-11T19:38:34Z | 315,881 | <p>Why do you feel that it needs to be synchronous?</p>
<p>If you want to ensure that only one of these is happening at a time, invoke all of the calls through a DeferredSemaphore so you can rate limit the actual invocations (to any arbitrary value).</p>
<p>If you want to be able to run multiple streams of these at different times, but don't care about concurrency limits, then you should at least separate reactor startup and teardown from the invocations (the reactor should run throughout the entire lifetime of the process).</p>
<p>If you just can't figure out how to express your application's logic in a reactor pattern, you can use deferToThread and write a chunk of purely synchronous code -- although I would guess this would not be necessary.</p>
| 2 | 2008-11-24T23:32:46Z | [
"python",
"twisted"
]
|
Python decorating functions before call | 282,393 | <p>I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?</p>
| 6 | 2008-11-11T22:42:44Z | 282,399 | <p>With:</p>
<pre><code>decorator(original_function)()
</code></pre>
<p>Without:</p>
<pre><code>original_function()
</code></pre>
<p>A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some <a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">documentation</a> might help clarify things.</p>
| 21 | 2008-11-11T22:45:52Z | [
"python",
"decorator"
]
|
Python decorating functions before call | 282,393 | <p>I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?</p>
| 6 | 2008-11-11T22:42:44Z | 282,816 | <pre><code>def original_function():
pass
decorated_function= decorator(original_function)
if use_decorated:
decorated_function()
else:
original_function()
</code></pre>
<p>Decorate only once, and afterwards choose which version to call.</p>
| 2 | 2008-11-12T02:26:08Z | [
"python",
"decorator"
]
|
Python decorating functions before call | 282,393 | <p>I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?</p>
| 6 | 2008-11-11T22:42:44Z | 812,743 | <p>Here is the recipe I came up with for the problem. I also needed to keep the signatures the same so I used the decorator module but you could re-jig to avoid that. Basically, the trick was to add an attribute to the function. The 'original' function is unbound so you need to pass in a 'self' as the first parameter so I added some extra code to check for that too.</p>
<pre><code># http://www.phyast.pitt.edu/~micheles/python/decorator-2.0.1.zip
from decorator import decorator, update_wrapper
class mustbe : pass
def wrapper ( interface_ ) :
print "inside hhh"
def call ( func, self, *args, **kwargs ) :
print "decorated"
print "calling %s.%s with args %s, %s" % (self, func.__name__, args, kwargs)
return interface_ ( self, *args, **kwargs )
def original ( instance , *args, **kwargs ) :
if not isinstance ( instance, mustbe ) :
raise TypeError, "Only use this decorator on children of mustbe"
return interface_ ( instance, *args, **kwargs )
call = decorator ( call, interface_ )
call.original = update_wrapper ( original, call )
return call
class CCC ( mustbe ):
var = "class var"
@wrapper
def foo ( self, param ) :
"""foo"""
print self.var, param
class SSS ( CCC ) :
@wrapper ( hidden_=True )
def bar ( self, a, b, c ) :
print a, b, c
if __name__ == "__main__" :
from inspect import getargspec
print ">>> i=CCC()"
i=CCC()
print ">>> i.var = 'parrot'"
i.var = 'parrot'
print ">>> i.foo.__doc__"
print i.foo.__doc__
print ">>> getargspec(i.foo)"
print getargspec(i.foo)
print ">>> i.foo(99)"
i.foo(99)
print ">>> i.foo.original.__doc__"
print i.foo.original.__doc__
print ">>> getargspec(i.foo.original)"
print getargspec(i.foo.original)
print ">>> i.foo.original(i,42)"
i.foo.original(i,42)
print ">>> j=SSS()"
j=SSS()
print ">>> j.bar(1,2,3)"
j.bar(1,2,3)
</code></pre>
| 1 | 2009-05-01T18:57:04Z | [
"python",
"decorator"
]
|
How can I download python .egg files, when behind a firewall | 282,907 | <p>I'm going to try out turbogears however I'm on windows vista.
however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment.
I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears.</p>
<p>if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment?</p>
<p>thanks so much!:)</p>
| 1 | 2008-11-12T03:15:07Z | 282,939 | <p>Add python to the firewall exceptions list. Just make sure you don't run any questionable code made in python, of course.</p>
| 1 | 2008-11-12T03:32:16Z | [
"python",
"windows",
"linux",
"cygwin",
"turbogears"
]
|
How can I download python .egg files, when behind a firewall | 282,907 | <p>I'm going to try out turbogears however I'm on windows vista.
however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment.
I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears.</p>
<p>if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment?</p>
<p>thanks so much!:)</p>
| 1 | 2008-11-12T03:15:07Z | 283,174 | <p>You can run TG <a href="http://docs.turbogears.org/1.0/InstallWindows" rel="nofollow">locally from windows</a>. The <code>tgsetup.py</code> method of installation uses <a href="http://pypi.python.org/pypi/setuptools/0.6c9" rel="nofollow">setuptools</a> which depends on being able to bring in <code>.egg</code> files from the internet. The best approach would be to open the firewall to eggs, as others suggested. TG has a <a href="http://www.turbogears.org/download/filelist.html" rel="nofollow">list of egg files</a> that you can try to bring manually (maybe from an open internet connection).
Installing an egg manually is possible, but <a href="http://www.turbogears.org/download/filelist.html" rel="nofollow">not recommended</a>.</p>
<p>If changing the firewall rules is not possible, you can use a Linux (bootable or virtual) installation that has a pre-configured TG package. For example, <a href="http://mirror.isoc.org.il/pub/fedora/releases/9/Everything/i386/os/Packages/TurboGears-1.0.4.4-2.fc9.noarch.rpm" rel="nofollow">Fedora has one</a>. This way, the TG package crosses (hopefully) the firewall as an <code>.rpm</code> file.</p>
| 3 | 2008-11-12T06:32:48Z | [
"python",
"windows",
"linux",
"cygwin",
"turbogears"
]
|
How can I download python .egg files, when behind a firewall | 282,907 | <p>I'm going to try out turbogears however I'm on windows vista.
however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment.
I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears.</p>
<p>if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment?</p>
<p>thanks so much!:)</p>
| 1 | 2008-11-12T03:15:07Z | 283,204 | <p>Perhaps the problem is not with the firewall per se, but with the fact that you need to use an HTTP proxy. If you do need to use a proxy, try setting the http_proxy environment variable. It might be that your firewall uses NTLM proxy authentication (which Python doesn't support); in this case, try setting up an <a href="http://ntlmaps.sourceforge.net/" rel="nofollow">APS proxy server</a> on your local machine, and point http_proxy to localhost.</p>
| 4 | 2008-11-12T06:56:14Z | [
"python",
"windows",
"linux",
"cygwin",
"turbogears"
]
|
How can I download python .egg files, when behind a firewall | 282,907 | <p>I'm going to try out turbogears however I'm on windows vista.
however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment.
I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears.</p>
<p>if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment?</p>
<p>thanks so much!:)</p>
| 1 | 2008-11-12T03:15:07Z | 283,271 | <p>You could use the old firewall hack... try throwing "?file.jpg" or "#file.jpg" on the end (sans quotes). The firewall may see this as you're trying to download an image file which it'll allow, the responding server probably won't care that you've attached a query string, and (I think) python will just see an egg.</p>
| 2 | 2008-11-12T07:52:24Z | [
"python",
"windows",
"linux",
"cygwin",
"turbogears"
]
|
How can I download python .egg files, when behind a firewall | 282,907 | <p>I'm going to try out turbogears however I'm on windows vista.
however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment.
I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears.</p>
<p>if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment?</p>
<p>thanks so much!:)</p>
| 1 | 2008-11-12T03:15:07Z | 285,270 | <p>This might not be what you are looking for, but you can <a href="http://www.mtu.net/~engstrom/ssh-proxy.php" rel="nofollow">bypass the proxy tunneling SSH</a>. Another possibility is using <a href="http://tor.eff.org" rel="nofollow">Tor</a>.</p>
| 0 | 2008-11-12T20:40:16Z | [
"python",
"windows",
"linux",
"cygwin",
"turbogears"
]
|
Django debugging with Emacs | 283,294 | <p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
| 20 | 2008-11-12T08:15:26Z | 284,058 | <p>I don't really know anything about it, but putting "debugging Python with emacs" into Google gave me this page about <a href="http://twistedmatrix.com/projects/core/documentation/howto/debug-with-emacs.html" rel="nofollow">debugging twisted with emacs</a>, so it seems to be possible.</p>
| 0 | 2008-11-12T14:16:45Z | [
"python",
"django",
"debugging",
"emacs"
]
|
Django debugging with Emacs | 283,294 | <p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
| 20 | 2008-11-12T08:15:26Z | 284,607 | <p>This isn't emacs specific, but you can use the Python debugger by adding the following to a Django view function:</p>
<p><code>import pdb; pdb.set_trace()</code></p>
<p>Now when you run the development server and view the page, your browser will appear to hang or load very slowly - switch over to your console, and you have access to the full debugger. You can inspect AND modify state of your application via an interactive shell - check out the Python documentation for the debugger, or this link for some <a href="http://www.onlamp.com/pub/a/python/2005/09/01/debugger.html">Python debugging examples</a></p>
<p><hr /></p>
<p>If all you need is logging, add the following to your <code>settings.py</code>:</p>
<pre><code>logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/tmp/mylog.log',
filemode = 'w'
)
</code></pre>
<p>Now you can log messages to <code>/tmp/mylog.log</code> by adding the following to any view function:</p>
<pre><code>import logging
logging.debug("Something happened")
</code></pre>
| 17 | 2008-11-12T16:57:37Z | [
"python",
"django",
"debugging",
"emacs"
]
|
Django debugging with Emacs | 283,294 | <p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
| 20 | 2008-11-12T08:15:26Z | 286,703 | <p>Here's something I found last night that will do exactly what you want when the program crashes:</p>
<p><a href="http://code.google.com/p/django-command-extensions/" rel="nofollow">http://code.google.com/p/django-command-extensions/</a></p>
<p>Once you install that you can run:</p>
<blockquote>
<p>python manage.py runserver_plus</p>
</blockquote>
<p>and you will have an interactive <code>AJAX console</code> on your <code>Error</code> page. (Obviously, be careful with the amount of access people have to this web server when running in that mode.)</p>
<p>GitHub: <a href="https://github.com/django-extensions/django-extensions" rel="nofollow">https://github.com/django-extensions/django-extensions</a></p>
<p>You can get Django Extensions by using pip or easy_install:</p>
<blockquote>
<p>$ pip install django-extensions or $ easy_install django-extensions</p>
</blockquote>
<p>If you want to install it from source, grab the git repository from GitHub and run setup.py:</p>
<blockquote>
<p>$ git clone git://github.com/django-extensions/django-extensions.git<br>
$ cd django-extensions<br>
$ python setup.py install</p>
</blockquote>
| 3 | 2008-11-13T10:01:41Z | [
"python",
"django",
"debugging",
"emacs"
]
|
Django debugging with Emacs | 283,294 | <p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
| 20 | 2008-11-12T08:15:26Z | 1,665,783 | <p>Start pdb like this:</p>
<p><kbd>M-x</kbd> <code>pdb</code></p>
<p>Then, start the Django development server:</p>
<pre><code>python manage.py runserver --noreload
</code></pre>
<p>Once you have the (Pdb) prompt, you need to do this:</p>
<pre><code>import sys
sys.path.append('/path/to/directory/containing/views.py')
</code></pre>
<p>Once you've done this, you should be able to set breakpoints normally. Just navigate to the line number you want, and </p>
<p><kbd>C-x</kbd> <kbd>SPC</kbd></p>
| 13 | 2009-11-03T07:33:57Z | [
"python",
"django",
"debugging",
"emacs"
]
|
Django debugging with Emacs | 283,294 | <p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
| 20 | 2008-11-12T08:15:26Z | 7,398,616 | <p>About the general non-emacs-exclusive way, there is a very nice screencast out there you might be interested in: <a href="http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/" rel="nofollow">http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/</a></p>
<p>The emacs integration described above doesn't work for me yet. It doesn't really seem to connect to the running application.</p>
<p>Further I consider this blog post here very interesting: <a href="http://web.archive.org/web/20101230072606/http://panela.blog-city.com/python_and_emacs_5_pdb_and_emacs.htm" rel="nofollow">http://web.archive.org/web/20101230072606/http://panela.blog-city.com/python_and_emacs_5_pdb_and_emacs.htm</a></p>
<p>cu
Roman</p>
| 0 | 2011-09-13T08:02:12Z | [
"python",
"django",
"debugging",
"emacs"
]
|
Django debugging with Emacs | 283,294 | <p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application?
I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
| 20 | 2008-11-12T08:15:26Z | 7,418,949 | <p>Because recent versions of Emacs python mode do support 'pdbtrack' functionality by default, all you need is just set up breakpoint in your code this way:</p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>Also, you have to start your Django application devserver from within Emacs shell: </p>
<p><kbd>M-x</kbd> <code>shell</code></p>
<p>And then, in the shell, start the Django development server:</p>
<pre><code>python ./manage.py runserver
</code></pre>
<p>P.S. No need for specific pdb sessions or --noreload flag. Noreload would require you to manually restart your applications and so I do not find this useful for Emacs.</p>
| 1 | 2011-09-14T15:27:25Z | [
"python",
"django",
"debugging",
"emacs"
]
|
Why would an "command not recognized" error occur only when a window is populated? | 283,431 | <p>My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it.</p>
<p>However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the </p>
<blockquote>
<p>'foo.py' is not recognized as an internal or external command, operable
program or batch file.</p>
</blockquote>
<p>I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.</p>
| 1 | 2008-11-12T09:38:53Z | 283,545 | <p>From the error message, it looks like you need to pass the full path of "foo.py" to your Popen call. Normally just having "foo.py" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog.</p>
<p>Secondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path.</p>
<p>So to be safe, something like:</p>
<pre><code>subprocess.Popen([r'C:\Python2.5\python.exe', r'C:\path\to\foo.py'])
</code></pre>
| 4 | 2008-11-12T10:36:43Z | [
"python",
"windows"
]
|
Why would an "command not recognized" error occur only when a window is populated? | 283,431 | <p>My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it.</p>
<p>However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the </p>
<blockquote>
<p>'foo.py' is not recognized as an internal or external command, operable
program or batch file.</p>
</blockquote>
<p>I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.</p>
| 1 | 2008-11-12T09:38:53Z | 286,436 | <p>The suggested answer seems to have fixed the problem. I also realized that I needed to use <strong>os.name</strong> to determine which OS is being used, then I can use the correct path format for loading the external Python file.</p>
| 0 | 2008-11-13T07:27:55Z | [
"python",
"windows"
]
|
Is it possible to use wxPython inside IronPython? | 283,447 | <p>When my IronPython program gets to the line </p>
<pre><code>import wx
</code></pre>
<p>I get this message:</p>
<pre><code>A first chance exception of type
'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll
Additional information: No module named _core_
</code></pre>
<p>although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines: </p>
<pre><code>sys.path.append('c:\\Python24\\Lib\\site-packages')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons')
</code></pre>
<p>which I hoped would let IronPython find everything it needed. </p>
| 4 | 2008-11-12T09:49:43Z | 283,520 | <p>No, this won't work. Wx bindings (like most other "python bindings") are actually compiled against CPython.</p>
<p>In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself. <a href="http://www.python.org/doc/2.5.2/ext/ext.html" rel="nofollow">This rather dry document explains the process.</a></p>
<p>Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called <a href="http://code.google.com/p/ironclad/" rel="nofollow">IronClad</a>) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.</p>
| 8 | 2008-11-12T10:27:31Z | [
"python",
"wxpython",
"ironpython"
]
|
Is it possible to use wxPython inside IronPython? | 283,447 | <p>When my IronPython program gets to the line </p>
<pre><code>import wx
</code></pre>
<p>I get this message:</p>
<pre><code>A first chance exception of type
'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll
Additional information: No module named _core_
</code></pre>
<p>although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines: </p>
<pre><code>sys.path.append('c:\\Python24\\Lib\\site-packages')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons')
</code></pre>
<p>which I hoped would let IronPython find everything it needed. </p>
| 4 | 2008-11-12T09:49:43Z | 284,800 | <p>While wxPython is unavailable for the reasons listed by @Ali, you may want to take a look at <a href="http://wxnet.sourceforge.net/">wx.NET</a>. You could use IronPython to call these assemblies instead, and it should be cross-platform (I'm assuming that's what you're after, or you would just use WinForms). If all you're looking for is API compatibility, I think you're out of luck :(</p>
| 5 | 2008-11-12T18:12:13Z | [
"python",
"wxpython",
"ironpython"
]
|
python list in sql query as parameter | 283,645 | <p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<p>"select name from studens where id = |IN THE LIST l|"</p>
<p>How do i accomlish this?</p>
| 45 | 2008-11-12T11:18:32Z | 283,706 | <p><a href="http://docs.python.org/library/stdtypes.html#str.join">string.join</a> the list values separated by commas, and use the <a href="http://docs.python.org/library/stdtypes.html#string-formatting">format operator</a> to form a query string.</p>
<pre><code>myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist))
</code></pre>
<p>(Thanks, <a href="http://stackoverflow.com/users/1199/blair-conrad">blair-conrad</a>)</p>
| 5 | 2008-11-12T11:49:37Z | [
"python",
"sql"
]
|
python list in sql query as parameter | 283,645 | <p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<p>"select name from studens where id = |IN THE LIST l|"</p>
<p>How do i accomlish this?</p>
| 45 | 2008-11-12T11:18:32Z | 283,713 | <p>The SQL you want is</p>
<pre><code>select name from studens where id in (1, 5, 8)
</code></pre>
<p>If you want to construct this from the python you could use</p>
<pre><code>l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'
</code></pre>
<p>The <a href="http://docs.python.org/library/functions.html#map">map</a> function will transform the list into a list of strings that can be glued together by commas using the <a href="http://docs.python.org/library/stdtypes.html#str.join">str.join</a> method.</p>
<p>Alternatively:</p>
<pre><code>l = [1, 5, 8]
sql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'
</code></pre>
<p>if you prefer <a href="http://docs.python.org/glossary.html#term-generator-expression">generator expressions</a> to the map function.</p>
<p>UPDATE: <a href="http://stackoverflow.com/users/10661/slott">S. Lott</a> mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might want</p>
<pre><code>select name from studens where id = 1 or id = 5 or id = 8
</code></pre>
<p>Generated by </p>
<pre><code>sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))
</code></pre>
| 12 | 2008-11-12T11:52:22Z | [
"python",
"sql"
]
|
python list in sql query as parameter | 283,645 | <p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<p>"select name from studens where id = |IN THE LIST l|"</p>
<p>How do i accomlish this?</p>
| 45 | 2008-11-12T11:18:32Z | 283,801 | <p>Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.</p>
<p>Here's a variant using a parameterised query that would work for both:</p>
<pre><code>placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)
</code></pre>
| 51 | 2008-11-12T12:30:10Z | [
"python",
"sql"
]
|
python list in sql query as parameter | 283,645 | <p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<p>"select name from studens where id = |IN THE LIST l|"</p>
<p>How do i accomlish this?</p>
| 45 | 2008-11-12T11:18:32Z | 4,233,213 | <p>I like bobince's answer:</p>
<pre><code>placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)
</code></pre>
<p>But I noticed this:</p>
<pre><code>placeholders= ', '.join(placeholder for unused in l)
</code></pre>
<p>Can be replaced with:</p>
<pre><code>placeholders= ', '.join(placeholder*len(l))
</code></pre>
<p>I find this more direct if less clever and less general. Here <code>l</code> is required to have a length (i.e. refer to an object that defines a <code>__len__</code> method), which shouldn't be a problem. But placeholder must also be a single character. To support a multi-character placeholder use:</p>
<pre><code>placeholders= ', '.join([placeholder]*len(l))
</code></pre>
| 2 | 2010-11-20T14:35:13Z | [
"python",
"sql"
]
|
python list in sql query as parameter | 283,645 | <p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<p>"select name from studens where id = |IN THE LIST l|"</p>
<p>How do i accomlish this?</p>
| 45 | 2008-11-12T11:18:32Z | 27,145,241 | <p>Solution for @umounted answer, because that broke with a one-element tuple, since (1,) is not valid SQL.:</p>
<pre><code>>>> random_ids = [1234,123,54,56,57,58,78,91]
>>> cursor.execute("create table test (id)")
>>> for item in random_ids:
cursor.execute("insert into test values (%d)" % item)
>>> sublist = [56,57,58]
>>> cursor.execute("select id from test where id in %s" % str(tuple(sublist)).replace(',)',')'))
>>> a = cursor.fetchall()
>>> a
[(56,), (57,), (58,)]
</code></pre>
<p>Other solution for sql string:</p>
<pre><code>cursor.execute("select id from test where id in (%s)" % ('"'+'", "'.join(l)+'"'))
</code></pre>
| -1 | 2014-11-26T09:16:45Z | [
"python",
"sql"
]
|
python list in sql query as parameter | 283,645 | <p>I have a python list, say l</p>
<pre><code>l = [1,5,8]
</code></pre>
<p>I want to write a sql query to get the data for all the elements of the list, say</p>
<p>"select name from studens where id = |IN THE LIST l|"</p>
<p>How do i accomlish this?</p>
| 45 | 2008-11-12T11:18:32Z | 39,024,751 | <p>For example, if you want the sql query:</p>
<pre><code>select name from studens where id in (1, 5, 8)
</code></pre>
<p>What about:</p>
<pre><code>my_list = [1, 5, 8]
cur.execute("select name from studens where id in %s" % repr(my_list).replace('[','(').replace(']',')') )
</code></pre>
| 0 | 2016-08-18T18:02:23Z | [
"python",
"sql"
]
|
Size of an open file object | 283,707 | <p>Is there a way to find the size of a file object that is currently open?</p>
<p>Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.</p>
| 33 | 2008-11-12T11:49:46Z | 283,718 | <p>If you have the file descriptor, you can use <code>fstat</code> to find out the size, if any. A more generic solution is to seek to the end of the file, and read its location there.</p>
| 4 | 2008-11-12T11:55:27Z | [
"python"
]
|
Size of an open file object | 283,707 | <p>Is there a way to find the size of a file object that is currently open?</p>
<p>Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.</p>
| 33 | 2008-11-12T11:49:46Z | 283,719 | <pre><code>$ ls -la chardet-1.0.1.tgz
-rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz
$ python
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('chardet-1.0.1.tgz','rb')
>>> f.seek(0,2)
>>> f.tell()
179218L
</code></pre>
<p>Adding ChrisJY's idea to the example</p>
<pre><code>>>> import os
>>> os.fstat(f.fileno()).st_size
179218L
>>>
</code></pre>
| 54 | 2008-11-12T11:55:30Z | [
"python"
]
|
Size of an open file object | 283,707 | <p>Is there a way to find the size of a file object that is currently open?</p>
<p>Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.</p>
| 33 | 2008-11-12T11:49:46Z | 283,725 | <p>Well, if the file object support the tell method, you can do:</p>
<pre><code>current_size = f.tell()
</code></pre>
<p>That will tell you were it is currently writing. If you write in a sequential way this will be the size of the file.</p>
<p>Otherwise, you can use the file system capabilities, i.e. <code>os.fstat</code> as suggested by others.</p>
| 7 | 2008-11-12T11:59:36Z | [
"python"
]
|
Size of an open file object | 283,707 | <p>Is there a way to find the size of a file object that is currently open?</p>
<p>Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.</p>
| 33 | 2008-11-12T11:49:46Z | 38,992,375 | <p>Another solution is using StringIO "if you are doing in-memory operations".</p>
<pre><code>with open(file_path, 'rb') as x:
body = StringIO()
body.write(x.read())
body.seek(0, 0)
</code></pre>
<p>Now <code>body</code> behaves like a file object with various attributes like <code>body.read()</code>. </p>
<p><code>body.len</code> gives the file size.</p>
| 1 | 2016-08-17T09:07:29Z | [
"python"
]
|
Pickled file won't load on Mac/Linux | 283,766 | <p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p>
<p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p>
<blockquote>
<pre><code>unpickle_file = cPickle.load(char_file)
</code></pre>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p>
<p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p>
<p><hr /></p>
<p><strong>Edit</strong> Here's the save code:</p>
<pre><code>def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
</code></pre>
<p>Here's the open code:</p>
<pre><code> def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
</code></pre>
| 4 | 2008-11-12T12:15:52Z | 283,802 | <p>Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data.</p>
<p>To open a file in binary mode you have to provide "b" as part of the mode string:</p>
<pre><code>char_file = open('pickle.char', 'rb')
</code></pre>
| 9 | 2008-11-12T12:30:35Z | [
"python",
"linux",
"osx",
"cross-platform"
]
|
Pickled file won't load on Mac/Linux | 283,766 | <p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p>
<p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p>
<blockquote>
<pre><code>unpickle_file = cPickle.load(char_file)
</code></pre>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p>
<p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p>
<p><hr /></p>
<p><strong>Edit</strong> Here's the save code:</p>
<pre><code>def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
</code></pre>
<p>Here's the open code:</p>
<pre><code> def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
</code></pre>
| 4 | 2008-11-12T12:15:52Z | 283,854 | <p>As mentioned by <a href="http://stackoverflow.com/questions/283766/pickled-file-wont-load-on-maclinux#283802">Adam</a>, the problem is likely to be the newline format of the pickle file.</p>
<p>Unfortunately, the real problem is actually caused on <em>save</em> rather than load. This may be recoverable if you're using text mode pickles, rather than binary. Try opening the file in universal newline mode, which will cause python to guess what the right line-endings are ie:</p>
<pre><code>char_file=open('filename.char','rU')
</code></pre>
<p>However, if you're using a binary format (cPickle.dump(file, 1)) you may have an unrecoverably corrupted pickle (even when loading in Windows) - if you're lucky and no \r\n characters show up then it may work, but as soon as this occurs you could end up with corrupted data, as there's no way to distinguish between a "real" \r\n code and one windows has inserted on seeing just \n.</p>
<p>The best way to handle things to be loaded in multiple platforms is to always save in binary mode. On your windows machine, when saving the pickle use:</p>
<pre><code>char_file = open('filename.char','wb')
cPickle.dumps(data, char_file)
</code></pre>
| 6 | 2008-11-12T12:57:32Z | [
"python",
"linux",
"osx",
"cross-platform"
]
|
Pickled file won't load on Mac/Linux | 283,766 | <p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p>
<p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p>
<blockquote>
<pre><code>unpickle_file = cPickle.load(char_file)
</code></pre>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p>
<p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p>
<p><hr /></p>
<p><strong>Edit</strong> Here's the save code:</p>
<pre><code>def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
</code></pre>
<p>Here's the open code:</p>
<pre><code> def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
</code></pre>
| 4 | 2008-11-12T12:15:52Z | 284,357 | <pre><code>self.file = open(self.file_name, 'w')</code></pre>
<p>Should be:</p>
<pre><code>self.file = open(self.file_name, 'wb')</code></pre>
<p>In your <code>createSaveFile</code> function, to save the file in binary mode (rather than text mode). You should also make sure you open the file in binary mode as well (rb).</p>
<p>If you don't use binary mode then Windows will convert all new-lines to \r\n and will effectively corrupt the file (at least as far as other OS's are concerned).</p>
| 2 | 2008-11-12T15:46:22Z | [
"python",
"linux",
"osx",
"cross-platform"
]
|
Pickled file won't load on Mac/Linux | 283,766 | <p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p>
<p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p>
<blockquote>
<pre><code>unpickle_file = cPickle.load(char_file)
</code></pre>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p>
<p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p>
<p><hr /></p>
<p><strong>Edit</strong> Here's the save code:</p>
<pre><code>def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
</code></pre>
<p>Here's the open code:</p>
<pre><code> def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
</code></pre>
| 4 | 2008-11-12T12:15:52Z | 9,357,720 | <p>Another way to get this error is to forget to close the output file after pickling. This can leave an incomplete file that fails in random ways during subsequent unpickling.</p>
| 4 | 2012-02-20T07:45:18Z | [
"python",
"linux",
"osx",
"cross-platform"
]
|
Pickled file won't load on Mac/Linux | 283,766 | <p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p>
<p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p>
<blockquote>
<pre><code>unpickle_file = cPickle.load(char_file)
</code></pre>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p>
<p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p>
<p><hr /></p>
<p><strong>Edit</strong> Here's the save code:</p>
<pre><code>def createSaveFile(self):
"""Create the data files to be saved and save them.
Creates a tuple comprised of a dictionary of general character information
and the character's skills dictionary."""
if self.file_name:
self.save_data = ({'Name':self.charAttribs.name,
<snip>
self.charAttribs.char_skills_dict)
self.file = open(self.file_name, 'w')
cPickle.dump(self.save_data, self.file)
self.file.close()
</code></pre>
<p>Here's the open code:</p>
<pre><code> def getCharFile(self, event): # wxGlade: CharSheet.<event_handler>
"""Retrieve pickled character file from disk."""
wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*"
openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(),
"", wildcard, wx.OPEN | wx.CHANGE_DIR)
if openDialog.ShowModal() == wx.ID_OK:
self.path = openDialog.GetPath()
try:
char_file = open(self.path, "r")
unpickle_file = cPickle.load(char_file)
char_data, char_skills = unpickle_file
self.displayCharacter(char_data, char_skills)
except IOError:
self.importError = wx.MessageDialog(self,
"The character file is not available!",
"Character Import Error", wx.OK | wx.ICON_ERROR)
self.importError.ShowModal()
self.importError.Destroy()
openDialog.Destroy()
</code></pre>
| 4 | 2008-11-12T12:15:52Z | 24,923,596 | <p>Use dos2unix tool</p>
<pre><code>dos2unix pickle.char
</code></pre>
| 0 | 2014-07-24T01:12:01Z | [
"python",
"linux",
"osx",
"cross-platform"
]
|
How to use Popen in Windows to invoke an external .py script and wait for its completion | 283,894 | <p>Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. </p>
<p>Regards. David </p>
<pre><code>#**********************************************************************
# Description:
# Zips the contents of a folder.
# Parameters:
# 0 - Input folder.
# 1 - Output zip file. It is assumed that the user added the .zip
# extension.
#**********************************************************************
# Import modules and create the geoprocessor
#
import sys, zipfile, arcgisscripting, os, traceback
gp = arcgisscripting.create()
# Function for zipping files. If keep is true, the folder, along with
# all its contents, will be written to the zip file. If false, only
# the contents of the input folder will be written to the zip file -
# the input folder name will not appear in the zip file.
#
def zipws(path, zip, keep):
path = os.path.normpath(path)
# os.walk visits every subdirectory, returning a 3-tuple
# of directory name, subdirectories in it, and filenames
# in it.
#
for (dirpath, dirnames, filenames) in os.walk(path):
# Iterate over every filename
#
for file in filenames:
# Ignore .lock files
#
if not file.endswith('.lock'):
gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file))
try:
if keep:
zip.write(os.path.join(dirpath, file),
os.path.join(os.path.basename(path),
os.path.join(dirpath, file)[len(path)+len(os.sep):]))
else:
zip.write(os.path.join(dirpath, file),
os.path.join(dirpath[len(path):], file))
except Exception, e:
gp.AddWarning(" Error adding %s: %s" % (file, e))
return None
if __name__ == '__main__':
try:
# Get the tool parameter values
#
infolder = gp.GetParameterAsText(0)
outfile = gp.GetParameterAsText(1)
# Create the zip file for writing compressed data. In some rare
# instances, the ZIP_DEFLATED constant may be unavailable and
# the ZIP_STORED constant is used instead. When ZIP_STORED is
# used, the zip file does not contain compressed data, resulting
# in large zip files.
#
try:
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
zipws(infolder, zip, True)
zip.close()
except RuntimeError:
# Delete zip file if exists
#
if os.path.exists(outfile):
os.unlink(outfile)
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
zipws(infolder, zip, True)
zip.close()
gp.AddWarning(" Unable to compress zip file contents.")
gp.AddMessage("Zip file created successfully")
except:
# Return any python specific errors as well as any errors from the geoprocessor
#
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo +
"\nError Info:\n " + str(sys.exc_type) +
": " + str(sys.exc_value) + "\n"
gp.AddError(pymsg)
msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n"
gp.AddError(msgs)
</code></pre>
| 1 | 2008-11-12T13:13:31Z | 284,199 | <ul>
<li><p><code>zip()</code> is a built-in function in Python. Therefore it is a bad practice to use <code>zip</code> as a variable name. <code>zip_</code> can be used instead of.</p></li>
<li><p><code>execfile()</code> function reads and executes a Python script.</p></li>
<li><p>It is probably that you actually need just <code>import zip_</code> in feedback.py instead of <code>execfile()</code>.</p></li>
</ul>
| 1 | 2008-11-12T14:58:20Z | [
"python",
"windows"
]
|
How to use Popen in Windows to invoke an external .py script and wait for its completion | 283,894 | <p>Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. </p>
<p>Regards. David </p>
<pre><code>#**********************************************************************
# Description:
# Zips the contents of a folder.
# Parameters:
# 0 - Input folder.
# 1 - Output zip file. It is assumed that the user added the .zip
# extension.
#**********************************************************************
# Import modules and create the geoprocessor
#
import sys, zipfile, arcgisscripting, os, traceback
gp = arcgisscripting.create()
# Function for zipping files. If keep is true, the folder, along with
# all its contents, will be written to the zip file. If false, only
# the contents of the input folder will be written to the zip file -
# the input folder name will not appear in the zip file.
#
def zipws(path, zip, keep):
path = os.path.normpath(path)
# os.walk visits every subdirectory, returning a 3-tuple
# of directory name, subdirectories in it, and filenames
# in it.
#
for (dirpath, dirnames, filenames) in os.walk(path):
# Iterate over every filename
#
for file in filenames:
# Ignore .lock files
#
if not file.endswith('.lock'):
gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file))
try:
if keep:
zip.write(os.path.join(dirpath, file),
os.path.join(os.path.basename(path),
os.path.join(dirpath, file)[len(path)+len(os.sep):]))
else:
zip.write(os.path.join(dirpath, file),
os.path.join(dirpath[len(path):], file))
except Exception, e:
gp.AddWarning(" Error adding %s: %s" % (file, e))
return None
if __name__ == '__main__':
try:
# Get the tool parameter values
#
infolder = gp.GetParameterAsText(0)
outfile = gp.GetParameterAsText(1)
# Create the zip file for writing compressed data. In some rare
# instances, the ZIP_DEFLATED constant may be unavailable and
# the ZIP_STORED constant is used instead. When ZIP_STORED is
# used, the zip file does not contain compressed data, resulting
# in large zip files.
#
try:
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
zipws(infolder, zip, True)
zip.close()
except RuntimeError:
# Delete zip file if exists
#
if os.path.exists(outfile):
os.unlink(outfile)
zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED)
zipws(infolder, zip, True)
zip.close()
gp.AddWarning(" Unable to compress zip file contents.")
gp.AddMessage("Zip file created successfully")
except:
# Return any python specific errors as well as any errors from the geoprocessor
#
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo +
"\nError Info:\n " + str(sys.exc_type) +
": " + str(sys.exc_value) + "\n"
gp.AddError(pymsg)
msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n"
gp.AddError(msgs)
</code></pre>
| 1 | 2008-11-12T13:13:31Z | 284,448 | <p>Yay ArcGIS.</p>
<p>Just to clarify how are you trying to call this script using popen, can you post some code?</p>
<p>If your invoking this script via another script in the ArcGIS environment, then the thing is, when you use Popen the script wont be invoked within the ArcGIS environment, instead it will be invoked within windows. So you will loose all real control over it.</p>
<p>Also just another ArcGIS comment you never initalize a license for the geoprocessor.</p>
<p>My suggestion refactor your code, into a module function that simply attempts to zip the files, if it fails print the message out to ArcGIS.</p>
<p>If you want post how you are calling it, and how this is being run.</p>
| 0 | 2008-11-12T16:15:35Z | [
"python",
"windows"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 284,110 | <p>You can use simple print statements, or any other way of writing to stdout. You can also invoke the Python debugger anywhere in your tests.</p>
<p>If you use <a href="https://web.archive.org/web/20081120065052/http://www.somethingaboutorange.com/mrl/projects/nose" rel="nofollow">nose</a> to run your tests (which I recommend), it will collect the stdout for each test and only show it to you if the test failed, so you don't have to live with the cluttered output when the tests pass.</p>
<p>nose also has switches to automatically show variables mentioned in asserts, or to invoke the debugger on failed tests.</p>
| 21 | 2008-11-12T14:33:31Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 284,192 | <p>I don't think this is quite what your looking for, there's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want.</p>
<p>You can use the <strong><a href="http://docs.python.org/library/unittest.html#id3">TestResult object</a></strong> returned by the <strong>TestRunner.run()</strong> for results analysis and processing. Particularly, TestResult.errors and TestResult.failures</p>
<p>About the TestResults Object:</p>
<p><a href="http://docs.python.org/library/unittest.html#id3">http://docs.python.org/library/unittest.html#id3</a></p>
<p>And some code to point you in the right direction:</p>
<pre><code>>>> import random
>>> import unittest
>>>
>>> class TestSequenceFunctions(unittest.TestCase):
... def setUp(self):
... self.seq = range(5)
... def testshuffle(self):
... # make sure the shuffled sequence does not lose any elements
... random.shuffle(self.seq)
... self.seq.sort()
... self.assertEqual(self.seq, range(10))
... def testchoice(self):
... element = random.choice(self.seq)
... error_test = 1/0
... self.assert_(element in self.seq)
... def testsample(self):
... self.assertRaises(ValueError, random.sample, self.seq, 20)
... for element in random.sample(self.seq, 5):
... self.assert_(element in self.seq)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)
testchoice (__main__.TestSequenceFunctions) ... ERROR
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... FAIL
======================================================================
ERROR: testchoice (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 11, in testchoice
ZeroDivisionError: integer division or modulo by zero
======================================================================
FAIL: testshuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 8, in testshuffle
AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
----------------------------------------------------------------------
Ran 3 tests in 0.031s
FAILED (failures=1, errors=1)
>>>
>>> testResult.errors
[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n File "<stdin>"
, line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')]
>>>
>>> testResult.failures
[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n File "<stdin>
", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')]
>>>
</code></pre>
| 14 | 2008-11-12T14:56:25Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 284,283 | <p>How about catching the exception that gets generated from the assertion failure? In your catch block you could output the data however you wanted to wherever. Then when you were done you could re-throw the exception. The test runner probably wouldn't know the difference. </p>
<p>Disclaimer: I haven't tried this with python's unit test framework but have with other unit test frameworks.</p>
| 0 | 2008-11-12T15:25:57Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 284,326 | <p>We use the logging module for this.</p>
<p>For example:</p>
<pre><code>import logging
class SomeTest( unittest.TestCase ):
def testSomething( self ):
log= logging.getLogger( "SomeTest.testSomething" )
log.debug( "this= %r", self.this )
log.debug( "that= %r", self.that )
# etc.
self.assertEquals( 3.14, pi )
if __name__ == "__main__":
logging.basicConfig( stream=sys.stderr )
logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
unittest.main()
</code></pre>
<p>That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.</p>
<p>My preferred method, however, isn't to spent a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.</p>
| 51 | 2008-11-12T15:38:03Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 284,706 | <p>I think I might have been overthinking this. One way I've come up with that does the job, is simply to have a global variable, that accumulates the diagnostic data.</p>
<p>Somthing like this:</p>
<pre><code>log1 = dict()
class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
if f.bar(t2) != 2:
log1("TestBar.runTest") = (f, t1, t2)
self.fail("f.bar(t2) != 2")
</code></pre>
<p>Thanks for the resplies. They have given me some alternative ideas for how to record information from unit tests. </p>
| 6 | 2008-11-12T17:38:52Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 288,568 | <p>Another option - start a debugger where the test fails.</p>
<p>Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.</p>
<p>Here's a terminal session on windows:</p>
<pre><code>C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
1 from unittest import TestCase
2 class MyTests(TestCase):
3 def test_foo(self):
4 x = 1
5 y = 2
6 -> self.assertEqual(x, y)
[EOF]
(Pdb)
</code></pre>
| 4 | 2008-11-13T22:28:25Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 13,688,397 | <p>Very late answer for someone that, like me, comes here looking for a simple and quick answer.</p>
<p>In Python 2.7 you could use an additional parameter <code>msg</code> to add information to the error message like this:</p>
<pre><code>self.assertEqual(f.bar(t2), 2, msg='{0}, {1}'.format(t1, t2))
</code></pre>
<p>Offical docs <a href="http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertEqual">here</a></p>
| 41 | 2012-12-03T17:17:16Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 18,791,576 | <p>inspect.trace will let you get local variables after an exception has been thrown. You can then wrap the unit tests with a decorator like the following one to save off those local variables for examination during the post mortem.</p>
<pre><code>import random
import unittest
import inspect
def store_result(f):
"""
Store the results of a test
On success, store the return value.
On failure, store the local variables where the exception was thrown.
"""
def wrapped(self):
if 'results' not in self.__dict__:
self.results = {}
# If a test throws an exception, store local variables in results:
try:
result = f(self)
except Exception as e:
self.results[f.__name__] = {'success':False, 'locals':inspect.trace()[-1][0].f_locals}
raise e
self.results[f.__name__] = {'success':True, 'result':result}
return result
return wrapped
def suite_results(suite):
"""
Get all the results from a test suite
"""
ans = {}
for test in suite:
if 'results' in test.__dict__:
ans.update(test.results)
return ans
# Example:
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
@store_result
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
return {1:2}
@store_result
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
return {7:2}
@store_result
def test_sample(self):
x = 799
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
return {1:99999}
suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)
from pprint import pprint
pprint(suite_results(suite))
</code></pre>
<p>The last line will print the returned values where the test succeeded and the local variables, in this case x, when it fails:</p>
<pre><code>{'test_choice': {'result': {7: 2}, 'success': True},
'test_sample': {'locals': {'self': <__main__.TestSequenceFunctions testMethod=test_sample>,
'x': 799},
'success': False},
'test_shuffle': {'result': {1: 2}, 'success': True}}
</code></pre>
<p>Har det gøy :-)</p>
| 1 | 2013-09-13T17:01:36Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 19,538,362 | <p>Expanding @F.C. 's answer, this works quite well for me:</p>
<pre><code>class MyTest(unittest.TestCase):
def messenger(self, message):
try:
self.assertEqual(1, 2, msg=message)
except AssertionError as e:
print "\nMESSENGER OUTPUT: %s" % str(e),
</code></pre>
| 0 | 2013-10-23T09:50:38Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 22,187,982 | <p>The method I use is really simple. I just log it as a warning so it will actually show up.
</p>
<pre><code>import logging
class TestBar(unittest.TestCase):
def runTest(self):
#this line is important
logging.basicConfig()
log = logging.getLogger("LOG")
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
log.warning(t1)
</code></pre>
| 4 | 2014-03-05T03:34:54Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 28,546,167 | <p>Use logging:</p>
<pre><code>import unittest
import logging
import inspect
import os
logging_level = logging.INFO
try:
log_file = os.environ["LOG_FILE"]
except KeyError:
log_file = None
def logger(stack=None):
if not hasattr(logger, "initialized"):
logging.basicConfig(filename=log_file, level=logging_level)
logger.initialized = True
if not stack:
stack = inspect.stack()
name = stack[1][3]
try:
name = stack[1][0].f_locals["self"].__class__.__name__ + "." + name
except KeyError:
pass
return logging.getLogger(name)
def todo(msg):
logger(inspect.stack()).warning("TODO: {}".format(msg))
def get_pi():
logger().info("sorry, I know only three digits")
return 3.14
class Test(unittest.TestCase):
def testName(self):
todo("use a better get_pi")
pi = get_pi()
logger().info("pi = {}".format(pi))
todo("check more digits in pi")
self.assertAlmostEqual(pi, 3.14)
logger().debug("end of this test")
pass
</code></pre>
<p>Usage:</p>
<pre><code># LOG_FILE=/tmp/log python3 -m unittest LoggerDemo
.
----------------------------------------------------------------------
Ran 1 test in 0.047s
OK
# cat /tmp/log
WARNING:Test.testName:TODO: use a better get_pi
INFO:get_pi:sorry, I know only three digits
INFO:Test.testName:pi = 3.14
WARNING:Test.testName:TODO: check more digits in pi
</code></pre>
<p>If you do not set <code>LOG_FILE</code>, logging will got to <code>stderr</code>.</p>
| 2 | 2015-02-16T16:38:21Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 30,038,630 | <p>You can use <code>logging</code> module for that.</p>
<p>So in the unit test code, use:</p>
<pre><code>import logging as log
def test_foo(self):
log.debug("Some debug message.")
log.info("Some info message.")
log.warning("Some warning message.")
log.error("Some error message.")
</code></pre>
<p>By default warnings and errors are outputted to <code>/dev/stderr</code>, so they should be visible on the console.</p>
<p>To customize logs (such as formatting), try the following sample:</p>
<pre><code># Set-up logger
if args.verbose or args.debug:
logging.basicConfig( stream=sys.stdout )
root = logging.getLogger()
root.setLevel(logging.INFO if args.verbose else logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO if args.verbose else logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
root.addHandler(ch)
else:
logging.basicConfig(stream=sys.stderr)
</code></pre>
| 1 | 2015-05-04T19:42:27Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 32,245,657 | <p>Admitting that I haven't tried it, the <a href="https://pythonhosted.org/testfixtures/logging.html" rel="nofollow">testfixtures' logging feature</a> looks quite useful...</p>
| 0 | 2015-08-27T09:32:26Z | [
"python",
"unit-testing"
]
|
Outputting data from unit test in python | 284,043 | <p>If I'm writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error? I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p>
<p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p>
<pre><code>class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
self.assertEqual(f.bar(t2), 2)
</code></pre>
<p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
| 76 | 2008-11-12T14:10:27Z | 36,178,137 | <p>What I do in these cases is to have a <code>log.debug()</code> with some messages in my application. Since the default logging level is <code>WARNING</code>, such messages don't show in the normal execution.</p>
<p>Then, in the unittest I change the logging level to <code>DEBUG</code>, so that such messages are shown while running them.</p>
<pre><code>import logging
log.debug("Some messages to be shown just when debugging or unittesting")
</code></pre>
<p>In the unittests:</p>
<pre><code># Set log level
loglevel = logging.DEBUG
logging.basicConfig(level=loglevel)
</code></pre>
<hr>
<hr>
<hr>
<p>See a full example:</p>
<p>This is <code>daikiri.py</code>, a basic class that implements a Daikiri with its name and price. There is method <code>make_discount()</code> that returns the price of that specific daikiri after applying a given discount:</p>
<pre><code>import logging
log = logging.getLogger(__name__)
class Daikiri(object):
def __init__(self, name, price):
self.name = name
self.price = price
def make_discount(self, percentage):
log.debug("Deducting discount...") # I want to see this message
return self.price * percentage
</code></pre>
<p>Then, I create a unittest <code>test_daikiri.py</code> that checks its usage:</p>
<pre><code>import unittest
import logging
from .daikiri import Daikiri
class TestDaikiri(unittest.TestCase):
def setUp(self):
# Changing log level to DEBUG
loglevel = logging.DEBUG
logging.basicConfig(level=loglevel)
self.mydaikiri = Daikiri("cuban", 25)
def test_drop_price(self):
new_price = self.mydaikiri.make_discount(0)
self.assertEqual(new_price, 0)
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>So when I execute it I get the <code>log.debug</code> messages:</p>
<pre><code>$ python -m test_daikiri
DEBUG:daikiri:Deducting discount...
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
</code></pre>
| 2 | 2016-03-23T12:24:52Z | [
"python",
"unit-testing"
]
|
Cross platform hidden file detection | 284,115 | <p>What is the best way to do cross-platform handling of hidden files?
(preferably in Python, but other solutions still appreciated)</p>
<p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
| 13 | 2008-11-12T14:35:29Z | 284,363 | <p>"Is there a standard way to deal with this?" Yes. Use a standard (i.e., POSIX-compliant) OS.</p>
<p>Since Windows is non-standard -- well -- there's no applicable standard. Wouldn't it be great if there was? I feel your pain.</p>
<p>Anything you try to do that's cross-platform like that will have Win32 oddities.</p>
<p>Your solution is -- for the present state of affairs -- excellent. At some point in the future, Microsoft may elect to write a POSIX-compliant OS. Until then, you're coping well with the situation.</p>
| -3 | 2008-11-12T15:47:54Z | [
"python",
"cross-platform",
"filesystems"
]
|
Cross platform hidden file detection | 284,115 | <p>What is the best way to do cross-platform handling of hidden files?
(preferably in Python, but other solutions still appreciated)</p>
<p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
| 13 | 2008-11-12T14:35:29Z | 284,439 | <p>We actually address this in a project we write. What we do is have a number of different "hidden file checkers" that are registered with a main checker. We pass each file through these to see if it should be hidden or not.</p>
<p>These checkers are not only for different OS's etc, but we plug into version control "ignored" files, and optional user overrides by glob or regular expression.</p>
<p>It mostly amounts to what you have done, but in a pluggable, flexible and extensible way.</p>
| 1 | 2008-11-12T16:11:11Z | [
"python",
"cross-platform",
"filesystems"
]
|
Cross platform hidden file detection | 284,115 | <p>What is the best way to do cross-platform handling of hidden files?
(preferably in Python, but other solutions still appreciated)</p>
<p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
| 13 | 2008-11-12T14:35:29Z | 6,365,265 | <p>Here's a script that runs on Python 2.5+ and should do what you're looking for:</p>
<pre><code>import ctypes
import os
def is_hidden(filepath):
name = os.path.basename(os.path.abspath(filepath))
return name.startswith('.') or has_hidden_attribute(filepath)
def has_hidden_attribute(filepath):
try:
attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath))
assert attrs != -1
result = bool(attrs & 2)
except (AttributeError, AssertionError):
result = False
return result
</code></pre>
<p>I added something similar to has_hidden_attribute to <a href="https://bitbucket.org/jaraco/jaraco.windows" rel="nofollow">jaraco.windows</a>. If you have jaraco.windows >= 2.3:</p>
<pre><code>from jaraco.windows import filesystem
def has_hidden_attribute(filepath):
return filesystem.GetFileAttributes(filepath).hidden
</code></pre>
<p>As Ben has pointed out, on Python 3.5, you can use the stdlib:</p>
<pre><code>import os, stat
def has_hidden_attribute(filepath):
return bool(os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)
</code></pre>
<p>Though you may still want to use jaraco.windows for the more Pythonic API.</p>
| 14 | 2011-06-15T22:37:28Z | [
"python",
"cross-platform",
"filesystems"
]
|
Cross platform hidden file detection | 284,115 | <p>What is the best way to do cross-platform handling of hidden files?
(preferably in Python, but other solutions still appreciated)</p>
<p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
| 13 | 2008-11-12T14:35:29Z | 15,236,292 | <p>Jason R. Coombs's answer is sufficient for Windows. And most POSIX GUI file managers/open dialogs/etc. probably follow the same "dot-prefix-means-hidden" convention as <code>ls</code>. But not Mac OS X.</p>
<p>There are at least four ways a file or directory can be hidden in Finder, file open panels, etc.:</p>
<ul>
<li>Dot prefix.</li>
<li>HFS+ invisible attribute.</li>
<li>Finder Info hidden flag.</li>
<li>Matches a special blacklist built into CoreFoundation (which is different on each OS versionâe.g., <code>~/Library</code> is hidden in 10.7+, but not in 10.6).</li>
</ul>
<p>Trying to write your own code to handle all of that is not going to be easy. And you'll have to keep it up-to-date, as I'm willing to bet the blacklist will change with most OS versions, Finder Info will eventually go from deprecated to completely unsupported, extended attributes may be supported more broadly than HFS+, â¦</p>
<p>But if you can require <code>pyobjc</code> (which is already included with recent Apple-supplied Python, and can be installed via <code>pip</code> otherwise), you can just call Apple's code:</p>
<pre><code>import Foundation
def is_hidden(path):
url = Foundation.NSURL.fileURLWithPath_(path)
return url.getResourceValue_forKey_error_(None, Foundation.NSURLIsHiddenKey, None)[0]
def listdir_skipping_hidden(path):
url = Foundation.NSURL.fileURLWithPath_(path)
fm = Foundation.NSFileManager.defaultManager()
urls = fm.contentsOfDirectoryAtURL_includingPropertiesForKeys_options_error_(
url, [], Foundation.NSDirectoryEnumerationSkipsHiddenFiles, None)[0]
return [u.path() for u in urls]
</code></pre>
<p>This should work on any Python that pyobjc supports, on OS X 10.6+. If you want 10.5 or earlier, directory enumeration flags didn't exist yet, so the only option is something like filtering something like <code>contentsOfDirectoryAtPath_error_</code> (or just <code>os.listdir</code>) on <code>is_hidden</code>.</p>
<p>If you have to get by without <code>pyobjc</code>, you can drop down to the <code>CoreFoundation</code> equivalents, and use <code>ctypes</code>. The key functions are <code>CFURLCopyResourcePropertyForKey</code> for <code>is_hidden</code> and <code>CFURLEnumeratorCreateForDirectoryURL</code> for listing a directory.</p>
<p>See <a href="http://pastebin.com/aCUwTumB">http://pastebin.com/aCUwTumB</a> for an implementation.</p>
<p>I've tested with:</p>
<ul>
<li>OS X 10.6, 32-bit python.org 3.3.0</li>
<li>OS X 10.8, 32-bit Apple 2.7.2</li>
<li>OS X 10.8, 64-bit Apple 2.7.2</li>
<li>OS X 10.8, 64-bit python.org 3.3.0</li>
</ul>
<p>It works as appropriate on each (e.g., it skips <code>~/Library</code> on 10.8, but shows it on 10.6). </p>
<p>It <em>should</em> work on any OS X 10.6+ and any Python 2.6+. If you need OS X 10.5, you need to use the old APIs (or <code>os.listdir</code>) and filter on <code>is_hidden</code>. If you need Python 2.5, change the <code>bytes</code> checks to <code>str</code> checks (which of course breaks 3.x) and the <code>with</code> to an ugly <code>try</code>/<code>finally</code> or manual releasing.</p>
<p>If anyone plans on putting this code into a library, I would strongly suggest checking for <code>pyobjc</code> first (<code>import Foundation</code> and, if you don't get an <code>ImportError</code> you win), and only using the <code>ctypes</code> code if it's not available.</p>
<hr>
<p>One last note:</p>
<p>Some people looking for this answer are trying to reinvent a wheel they don't need to.</p>
<p>Often, when people are doing something like this, they're building a GUI and want to, e.g., show a file browsers with an option to hide or show hidden files. Many of the popular cross-platform GUI frameworks (Qt, wx, etc.) have this support built in. (Also, many of them are open source, so you can read their code to see how they do it.)</p>
<p>That may not answer your questionâe.g., they may just be passing a "filter hidden files" flag to the platform's native file-browser dialog, but you're trying to build a console-mode file-browser and can't do that. But if it does, just use it.</p>
| 7 | 2013-03-05T23:42:04Z | [
"python",
"cross-platform",
"filesystems"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.