Re: How to parse this line of code manually

2007-08-27 Thread Davy
On Aug 28, 11:00 am, Davy <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> It is well known that Python is appreciated for its merit of concise.
> However, I found the over concise code is too hard to understand for
> me.
>
> Consider, for instance,
> def known_edits2(word):
> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in
> NWORDS)
>
> Shall I understand the code in set() as
> for e2 in edits1(e1) {
> if e2 in NWORDS {
> for e1 in edits1(word) {
>  e2
> }
> }
>
> }
>
[SNIP]
Hi all, I figured it myself. It is left to righ parse, right?
So the above one is like
for e1 in edits1(word) {
for e2 in edits1(e1) {
if e2 in NWORDS {
push e2 to set
}
}
}
> And a general question is: Is there any tip available to understand
> the code in one line, or what's the parsing priority (left to right,
> right to left, or other possibilities)
>
> Any suggestions are welcome!
>
> The code is a simple spell checker 
> fromhttp://www.norvig.com/spell-correct.html
>
> Best regards,
> Davy


-- 
http://mail.python.org/mailman/listinfo/python-list


How to parse this line of code manually

2007-08-27 Thread Davy
Hi all,

It is well known that Python is appreciated for its merit of concise.
However, I found the over concise code is too hard to understand for
me.

Consider, for instance,
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in
NWORDS)

Shall I understand the code in set() as
for e2 in edits1(e1) {
if e2 in NWORDS {
for e1 in edits1(word) {
 e2
}
}
}

And a general question is: Is there any tip available to understand
the code in one line, or what's the parsing priority (left to right,
right to left, or other possibilities)

Any suggestions are welcome!

The code is a simple spell checker from
http://www.norvig.com/spell-correct.html

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to parse this line of code manually

2007-08-29 Thread Davy
On Aug 28, 7:28 pm, Dustan <[EMAIL PROTECTED]> wrote:
> On Aug 28, 2:59 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On 2007-08-28, Davy <[EMAIL PROTECTED]> wrote:
>
> > > On Aug 28, 11:00 am, Davy <[EMAIL PROTECTED]> wrote:
> > >> Hi all,
>
> > >> It is well known that Python is appreciated for its merit of concise.
> > >> However, I found the over concise code is too hard to understand for
> > >> me.
>
> > >> Consider, for instance,
> > >> def known_edits2(word):
> > >> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in
> > >> NWORDS)
>
> > >> Shall I understand the code in set() as
> > >> for e2 in edits1(e1) {
> > >> if e2 in NWORDS {
> > >> for e1 in edits1(word) {
> > >>  e2
> > >> }
> > >> }
>
> > >> }
>
> > > [SNIP]
> > > Hi all, I figured it myself. It is left to righ parse, right?
> > > So the above one is like
> > > for e1 in edits1(word) {
> > > for e2 in edits1(e1) {
> > > if e2 in NWORDS {
> > > push e2 to set
> > > }
> > > }
> > > }
>
> > This is correct, although I am not sure what language you are using here, it
> > looks like a strange mix of Python and C to me.
>
> > >> Any suggestions are welcome!
>
> > The idea is known as List comprehension (for lists, obviously), and comes 
> > from
> > functional programming, Bird & Wadler used it in their book.
>
> > The notation is very close to mathematics:
>
> >  { e2 | e1: edits(word), e2: edits(e1) in NWORDS }
>
> > or in LaTeX:
>
> > $\{ e_2 | \forall e_1: \mathrm{edits}(\mathrm{words}),
> >   \forall e_2: \mathrm{edits}(e_1) \in \mathrm{NWORDS} \}$
>
> > :-)
>
> > (which in words is something like: collect values e2, where e1 comes from
> > 'edits(word)', e2 comes from 'edits(e1)', and e2 in NWORDS)
>
> For more 
> examples:http://docs.python.org/tut/node7.html#SECTION00714
[SNIP]
Hi Hofkamp and Dustan,

Thank you for your help :)

Davy
>
> A 'list comprehension' with parentheses instead of square-brackets
> creates a generator instead of a list, which can be more memory-
> efficient and allows for lazy evaluation.- Hide quoted text -
>
> - Show quoted text -


-- 
http://mail.python.org/mailman/listinfo/python-list


How to use list as key of dictionary?

2007-11-05 Thread Davy
Hi all,

We know that list cannot be used as key of dictionary. So, how to work
around it?

For example, there is random list like l=[1,323,54,67].

Any suggestions are welcome!

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use list as key of dictionary?

2007-11-06 Thread Davy
Hi Matimus and Boris,

Thank you :)

And a further question about vector above rank 1, how can I use it as
the key of dictionary?

For example, if I have list like L=[[1,2,3],[4,5,6,7]],
Then I do L_tuple = tuple(L)
>>> L_tuple = ([1,2,3],[4,5,6,7])
But {L_tuple:'hello'} cause an error?

Best regards,
Davy

On Nov 6, 3:09 pm, Matimus <[EMAIL PROTECTED]> wrote:
> On Nov 5, 10:53 pm, Davy <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
>
> > We know that list cannot be used as key of dictionary. So, how to work
> > around it?
>
> > For example, there is random list like l=[1,323,54,67].
>
> > Any suggestions are welcome!
>
> > Best regards,
> > Davy
>
> Use a tuple instead.
>
> >>> d = {}
> >>> d[tuple([1,2,3,4])] = 'hello world'
> >>> d
>
> {(1, 2, 3, 4): 'hello world'}>>> d[1,2,3,4]
>
> 'hello world'
>
> Matt


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to use list as key of dictionary?

2007-11-06 Thread Davy
And there may be more complex list(vector like 3 or 4 dimentional data
structure), is there any easy method to tackle this problem?

Any suggestions are welcome!

Best regards,
Davy

On Nov 6, 4:50 pm, Davy <[EMAIL PROTECTED]> wrote:
> Hi Matimus and Boris,
>
> Thank you :)
>
> And a further question about vector above rank 1, how can I use it as
> the key of dictionary?
>
> For example, if I have list like L=[[1,2,3],[4,5,6,7]],
> Then I do L_tuple = tuple(L)>>> L_tuple = ([1,2,3],[4,5,6,7])
>
> But {L_tuple:'hello'} cause an error?
>
> Best regards,
> Davy
>
> On Nov 6, 3:09 pm, Matimus <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Nov 5, 10:53 pm, Davy <[EMAIL PROTECTED]> wrote:
>
> > > Hi all,
>
> > > We know that list cannot be used as key of dictionary. So, how to work
> > > around it?
>
> > > For example, there is random list like l=[1,323,54,67].
>
> > > Any suggestions are welcome!
>
> > > Best regards,
> > > Davy
>
> > Use a tuple instead.
>
> > >>> d = {}
> > >>> d[tuple([1,2,3,4])] = 'hello world'
> > >>> d
>
> > {(1, 2, 3, 4): 'hello world'}>>> d[1,2,3,4]
>
> > 'hello world'
>
> > Matt- Hide quoted text -
>
> - Show quoted text -


-- 
http://mail.python.org/mailman/listinfo/python-list


List to Tuple and Tuple to List?

2007-11-06 Thread Davy
Hi all,

I am curious about whether there is function to fransform pure List to
pure Tuple and pure Tuple to pure List?

For example,

I have list L = [[1,2,3],[4,5,6]]
something list2tuple() will have T=list2tuple(L)=((1,2,3),(4,5,6))

And the tuple2list()

Any suggestions are welcome!

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


How to link different site-packages to different Python?

2007-11-09 Thread Davy
Hi all,

I have Python 2.4 and 2.5 in my PC. And PythonWin is installed as IDE.

When I tried to use site-packages "Numpy", I installed the both
version (i.e. for 2.4 and 2.5).

Python 2.4 and Numpy for it work together well.

But when I type "from numpy import *" in Python 2.5. It throw out an
error indicate that the numpy library is link to Python 2.4 package?
How to fix this problem?


The error pasted below is copied from Python 2.5 PythonWin console:
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Program Files\nupic-1.4\lib\python2.4\site-packages\numpy
\__init__.py", line 39, in 
import core
  File "C:\Program Files\nupic-1.4\lib\python2.4\site-packages\numpy
\core\__init__.py", line 5, in 
import multiarray
ImportError: Module use of python24.dll conflicts with this version of
Python.

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


defaultdict and dict?

2007-11-09 Thread Davy
Hi all,

In Python 2.5 document, defaultdict is called high performance
container. From document, we can know defaultdict is subclass of dict.
So, why defaultdict have higher performance than dict? And at what
circumstance, we can make use of such high performance?

That is, when use defaultdict and when use dict? Any suggestions are
welcome!

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


How to get a set of keys with largest values?

2007-11-12 Thread Davy
Hi all,

I have a dictionary with n elements, and I want to get the m(m<=n)
keys with the largest values.

For example, I have dic that includes n=4 elements, I want m=2 keys
have the largest values)
dic = {0:4,3:1,5:2,7:8}
So, the the largest values are [8,4], so the keys are [7,0].

Is there any fast way to implement this algorithm?
Any suggestions are welcome!

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a set of keys with largest values?

2007-11-12 Thread Davy
On Nov 12, 8:54 pm, Jeff <[EMAIL PROTECTED]> wrote:
> Why are you doing that with key-value pairs?  Why not with the array
> module or lists?

Hi,

The original question is a bit complex. I have to implement a sparse
matrix which use a dict of dict implementation.
For example, sp_mat = {1:{2:1,3:4},2:{4:6,8:9}}.

And I want to get m key with the largest values in each row? Any good
ideas?

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Define key in nlargest() of heapq?

2007-11-12 Thread Davy
Hi all,

I have a dictionary with n elements, and I want to get the m(m<=n)
keys with the largest values.

For example, I have dic that includes n=4 elements, I want m=2 keys
have the largest values)
dic = {0:4,3:1,5:2,7:8}
So, the the largest values are [8,4], so the keys are [7,0].

How to do this by nlargest() of heapq? I have tried
nlargest(2,dic,key),
the interpreter give out:
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'key' is not defined

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Define key in nlargest() of heapq?

2007-11-12 Thread Davy
Hi Raymond,

Your code work well, thank you :)

Best regards,
Davy

On Nov 13, 11:33 am, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On Nov 12, 6:56 pm, Davy <[EMAIL PROTECTED]> wrote:
>
> > I have a dictionary with n elements, and I want to get the m(m<=n)
> > keys with the largest values.
>
> > For example, I have dic that includes n=4 elements, I want m=2 keys
> > have the largest values)
> > dic = {0:4,3:1,5:2,7:8}
> > So, the the largest values are [8,4], so the keys are [7,0].
>
> > How to do this by nlargest() of heapq? I have tried
> > nlargest(2,dic,key),
>
> Try this:
>
> >>> from heapq import nlargest
> >>> dic = {0:4,3:1,5:2,7:8}
> >>> from operator import itemgetter
> >>> nlargest(2, dic, dic.__getitem__)
>
> [7, 0]
>
> Raymond


-- 
http://mail.python.org/mailman/listinfo/python-list


Loop three lists at the same time?

2007-11-13 Thread Davy
Hi all,

I have three lists with the same length. Is there any method to loop
the three lists without a loop counter?

Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


function call problem in class?

2007-11-13 Thread Davy
Hi all,

I have write a simple class, I want the function two() to call private
function __one(), but there is an error :
NameError: global name '_simple__one' is not defined, how to work
around it

class simple:
def __one(self):
print "Hello"
def two(self):
__one()
print "world"

if __name__ == '__main__':
s = simple()
s.two()

Any suggestion is welcome!
Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function call problem in class?

2007-11-14 Thread Davy
On Nov 14, 4:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 14 Nov 2007 04:51:57 -0300, Davy <[EMAIL PROTECTED]> escribió:
>
> > I have write a simple class, I want the function two() to call private
> > function __one(), but there is an error :
> > NameError: global name '_simple__one' is not defined, how to work
> > around it
>
> > class simple:
> > def __one(self):
> > print "Hello"
> > def two(self):
> > __one()
> > print "world"
>
> > if __name__ == '__main__':
> > s = simple()
> > s.two()
>
> Note that your problem is not related to mangled names: replacing __one by  
> one raises a similar exception.
> Remember that "self" is not implicit: you must use self.__one()
Hi Gabriel,

Thank you. now my code work well )

Davy

>
> "private" methods (and atributes in general) use a single underscore:  
> _one. Double underscores __one are reserved for the (rare) cases when you  
> want to ensure unique names (or name clashes are expected).
>
> --
> Gabriel Genellina


-- 
http://mail.python.org/mailman/listinfo/python-list

Tkinter Problem?

2007-11-19 Thread Davy
Hi all,

I have written a simple Tkinter program, that is draw a rectangle in a
canvas, when I press Up key, the rectangle move up. But the program
seems work not properly? My environment is Python2.5+PythonWin.

##--
from Tkinter import *

class MyApp:
def __init__(self,parent):
self.myContainer1 = Frame(parent)
self.myContainer1.pack()
self.canv = Canvas(relief=SUNKEN)
self.canv.config(width = 300,height=300)
self.canv.pack()
self.canv.create_rectangle(100,100,150,150,tags="rect")
self.canv.bind('',self._onUpKey)
self.canv.bind('', self._onReturnKey)
def _onUpKey(self,event):
self.canv.move(tagOrId,xAmount=0,yAmount=10)
def _onReturnKey(self,event):
print 'Hello world'


root = Tk()
myapp = MyApp(root)
root.mainloop()

##--

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


(Tkinter) Can I bind a key to Canvas?

2007-11-20 Thread Davy
Hi all,

I have a canvas and a rectangle draw on it. Can I bind a key(e.g. UP)
to the canvas and make the rectangle move up? Or shall I bind the key
to rectangle(I don't think so, because it is not a widget)?

Any suggestions are welcome!
Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Tkinter) Can I bind a key to Canvas?

2007-11-20 Thread Davy
I have tried key and mouse click (when receive a event, print some
diagnose information ). I found mouse click work well in canvas but
key not work well.

It seems canvas cannot get key event?

self.canv.bind('',self._onUpKey) ## don't work
self.canv.bind('', self._onClick) ## work

Any suggestion?

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


How to make a standalone Python/Tk program?

2007-11-20 Thread Davy
Hi all,

How to make a standalone Python/Tk program(e.g. exe file on Windows)?
Any suggestions are welcome!

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Problem?

2007-11-20 Thread Davy
Hi all,

I have solved the problem after read some code. Because Tk.Canvas do
not have a focus, it does not receive a key input. The solution is
bind key input to the highest level 'root'

root.bind('',self._onUpKey)

Davy

On Nov 20, 10:13 am, Davy <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I have written a simple Tkinter program, that is draw a rectangle in a
> canvas, when I press Up key, the rectangle move up. But the program
> seems work not properly? My environment is Python2.5+PythonWin.
>
> ##--
> from Tkinter import *
>
> class MyApp:
> def __init__(self,parent):
> self.myContainer1 = Frame(parent)
> self.myContainer1.pack()
> self.canv = Canvas(relief=SUNKEN)
> self.canv.config(width = 300,height=300)
> self.canv.pack()
> self.canv.create_rectangle(100,100,150,150,tags="rect")
> self.canv.bind('',self._onUpKey)
> self.canv.bind('', self._onReturnKey)
> def _onUpKey(self,event):
> self.canv.move(tagOrId,xAmount=0,yAmount=10)
> def _onReturnKey(self,event):
> print 'Hello world'
>
> root = Tk()
> myapp = MyApp(root)
> root.mainloop()
>
> ##--
>
> Best regards,
> Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Introspect the class name of object?

2007-11-21 Thread Davy
Hi all,

How to get the class name of an object from an introspect way?
For example,
Class cls:pass

obj = cls()

I want to get function(obj) = 'cls'

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there pointer * in Python?

2007-11-22 Thread Davy
Hi all,

When I read "programming python", I found there is a code like
def parse(self, *text):
while text is a string. What's "*" mean?(Does it mean pointer like in
C?)

And I recall there is "**args" in Python, what's "**" mean?

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


How to debug Python program with GUI (Tkinter)?

2007-11-28 Thread Davy
Hi all,

How to debug Python program with GUI, especially Tkinter? My debug
environment is PythonWin.

For example, when I single step in the program, the step will go to
mainloop() and always loop there. How can I know where the program is
processed?

Any suggestions are welcome!
Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Why use Slot? from Peter Norvig's AI code

2007-12-04 Thread Davy
Hi all,

When reading Python source code of Peter Norvig's AI book, I found it
hard for me to understand the idea of slot (function nested in
function). Please see "program()" nested in "make_agent_program()",
why not use program() directly?

## http://aima-python.googlecode.com/svn/trunk/agents.py
class Agent (Object):
"""An Agent is a subclass of Object with one required slot,
.program, which should hold a function that takes one argument,
the
percept, and returns an action. (What counts as a percept or
action
will depend on the specific environment in which the agent
exists.)
Note that 'program' is a slot, not a method.  If it were a method,
then the program could 'cheat' and look at aspects of the agent.
It's not supposed to do that: the program can only look at the
percepts.  An agent program that needs a model of the world (and
of
the agent itself) will have to build and maintain its own model.
There is an optional slots, .performance, which is a number giving
the performance measure of the agent in its environment."""

def __init__(self):
self.program = self.make_agent_program()
self.alive = True
self.bump = False

def make_agent_program (self):

def program(percept):
return raw_input('Percept=%s; action? ' % percept)
return program

def can_grab (self, obj):
"""Returns True if this agent can grab this object.
Override for appropriate subclasses of Agent and Object."""
return False


Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Profiler GUI like Matlab?

2007-12-06 Thread Davy
Hi all,

Is there any Python Profiler GUI like Matlab? I found the Matlab
Profiler is very intuitive and easy to use.

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


re.sub() problem (regular expression)

2007-12-13 Thread Davy
Hi all,

I have read a re.sub() that confused me.

s = 'P & Q'
s = re.sub(r'([a-zA-Z0-9_.]+)', r'Expr("\1")', s)

What's "\1" and the whole re.sub() mean?

Best regards,
Davy
-- 
http://mail.python.org/mailman/listinfo/python-list


Python's regular expression?

2006-05-08 Thread Davy
Hi all,

I am a C/C++/Perl user and want to switch to Python (I found Python is
more similar to C).

Does Python support robust regular expression like Perl?

And Python and Perl's File content manipulation, which is better?

Any suggestions will be appreciated!
Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's regular expression?

2006-05-08 Thread Davy
Hi Mirco,

Thank you!

More similar than Perl ;-)

And what's 'integrated' mean (must include some library)?

I like C++ file I/O, is it 'low' or 'high'? 

Regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's regular expression?

2006-05-08 Thread Davy
By the way, is there any tutorial talk about how to use the Python
Shell (IDE). I wish it simple like VC++ :)

Regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


PythonWin's Check (any other Lint tool) ?

2006-05-09 Thread Davy
Hi all,

I am using PythonWin from ActivePython. And I use the GUI button
'Check' to check the .py file.

But the Check did not give out a check list. It just show "Check
failed" or "Check successful".

Is the Check list saved in other where or is there any other Lint tool?

Any suggestions will be appreciated!
Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Why 3.0/5.0 = 0.59999...

2006-05-09 Thread Davy
Hi all,

I used to be a Matlab user. And want to use Python to replace some
Matlab work.

When I type 3.0/5.0, the result is 0.5...

Is there some precision loss? And how to overcome it?

Any suggestions will be appreciated!
Best regards,
Davy

-- 
http://mail.python.org/mailman/listinfo/python-list


Thread Tkinter problem

2008-12-03 Thread Davy
Hi all,

I am using thread and tkinter to write some simple programs and
solidify my understanding of Python thread/GUI programing. The scheme
is thread + queue + GUI. One child thread (gen_board_thread) generate
board and insert data into queue infinitely. Meanwhile, the main
thread canvas widget get the board data from queue.

I assume the program will run forever if don't close them explicitly,
but the fact is contrary to my understanding. It seems the child
thread insert data till queue is full, then the main thread eat the
data till the queue is empty, and the main thread starve(when timeout
option is set) and die. So the two thread work like two function call,
but not two thread!

Is this situation caused by deadlock(I guess main thread has higher
priority)? Or how can I know whether the child thread is still alive?
Ultimately, how to solve the problem?

The code are attached.
Any suggestion will be appreciated :-)
Best regards,
Davy

//-Code below---
from Tkinter import *
import thread
import Queue
##import time

x = 3 ## vertical
y = 5 ## horizontal
block_width = 10
block_height = 10
canvas_width = x * block_width
canvas_height = y * block_height

data_queue = Queue.Queue(20)

board_1 = [[1,0,1],
 [0,1,1],
 [1,0,0],
 [0,0,1],
 [0,1,0]]

board_2 = [[0,1,0],
 [1,0,0],
 [0,1,1],
 [1,1,0],
 [1,0,1]]

def gen_board_thread():
## Problem: the thread seems to be deadlock or killed or postponed
after execution was taken over by main thread draw_canvas_loop()
print 'enter here'
gen_flip = 1
while(data_queue.full() == False):
##print '???'
##time.sleep(0.1)
if (gen_flip == 1):
gen_flip = 0
data = board_1
else:
gen_flip = 1
data = board_2
data_queue.put(data)
print 'put', data_queue.qsize()

def create_canvas(root,canvas_width,canvas_height,):
canvas = Canvas(root, width=canvas_width, height=canvas_height,
bg='white')
canvas.pack(expand=YES)
return canvas

def draw_canvas_loop(canvas_b):
board = data_queue.get(block = True, timeout=1)
print 'get', data_queue.qsize()
draw_canvas(board, canvas_b, x, y, block_width, block_height)
canvas_b.after(300, lambda:draw_canvas_loop(canvas_b))


def draw_canvas(board, canvas_b, x, y, block_width, block_height):
##canvas_b.after(3000)
##time.sleep(3)
for j in range(y):
for i in range(x):
if board[j][i] == 1:
color = 'black'
else:
color = 'white'
start_x = block_width * i
start_y = block_height * j
end_x = start_x + block_width
end_y = start_y + block_height
canvas_b.create_rectangle
(start_x,start_y,end_x,end_y,fill=color)

if __name__ == '__main__':
root = Tk()
root.title('Tetris')
canvas = create_canvas(root,canvas_width,canvas_height)
thread.start_new(gen_board_thread,())
draw_canvas_loop(canvas)
mainloop()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Thread Tkinter problem

2008-12-03 Thread Davy
On Dec 4, 11:13 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>  "Davy" <[EMAIL PROTECTED]> wrote:
> >     while(data_queue.full() == False):
>
> This will fill the queue and stop.
> Use while true and if queue not full...
Hi Hendrik,

It works, thank you:)

Davy
>
> - Hendrik

--
http://mail.python.org/mailman/listinfo/python-list


time.sleep() and Tkinter after()?

2008-12-03 Thread Davy
Hi all,

I have used Tkinter after() to do loop update GUI in my previous post.
See 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/6b616abc236c345b/7df7684d33c969c5#7df7684d33c969c5

And I tried to change after() to time.sleep(), but it seems doesn't
work at all, the Queue send and receive data properly, but the GUI
didn't even appear?

//-code changed-
def draw_canvas_loop(canvas_b):
while (True):
board = data_queue.get(block = True, timeout=2)
print 'get', data_queue.qsize()
draw_canvas(board, canvas_b, x, y, block_width, block_height)
time.sleep(0.3)
##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b))
//

So, can I use time.sleep() in GUI application? Or Tkinter scheduler
just ignore the sleep() function?

And if I use after(), will the code form a recursive function call,
and the memory usage will boost as the program goes (I have watched
the task manager in WinXP and find the python.exe eat more and more
memory...).
//--code---
def draw_canvas_loop(canvas_b):
board = data_queue.get(block = True, timeout=1)
print 'get', data_queue.qsize()
draw_canvas(board, canvas_b, x, y, block_width, block_height)
canvas_b.after(300, lambda:draw_canvas_loop(canvas_b))
//-----

Best regards,
Davy
--
http://mail.python.org/mailman/listinfo/python-list


Re: Thread Tkinter problem

2008-12-03 Thread Davy
On Dec 4, 9:08 am, Davy <[EMAIL PROTECTED]> wrote:
> On Dec 4, 11:13 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:>  "Davy" 
> <[EMAIL PROTECTED]> wrote:
> > >     while(data_queue.full() == False):
>
> > This will fill the queue and stop.
> > Use while true and if queue not full...
>
> Hi Hendrik,
>
> It works, thank you:)
Add changed code:
//--code changed ---
def gen_board_thread():
print 'enter here'
gen_flip = 1
while(True):
time.sleep(0.3)
if (data_queue.full() == False):
if (gen_flip == 1):
gen_flip = 0
data = board_1
else:
gen_flip = 1
data = board_2
    data_queue.put(data)
print 'put', data_queue.qsize()
//
>
> Davy
>
>
>
>
>
> > - Hendrik- Hide quoted text -
>
> - Show quoted text -

--
http://mail.python.org/mailman/listinfo/python-list


Re: time.sleep() and Tkinter after()?

2008-12-04 Thread Davy
On Dec 5, 3:05 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> "Davy" <[EMAIL PROTECTED]> wrote:
> > I have used Tkinter after() to do loop update GUI in my previous post.
> > And I tried to change after() to time.sleep(), but it seems doesn't
> > work at all, the Queue send and receive data properly, but the GUI
> > didn't even appear?
>
> > //-code changed-
> > def draw_canvas_loop(canvas_b):
> >     while (True):
> >         board = data_queue.get(block = True, timeout=2)
>
> Do you want it to block, or do you want it to time out?

Hi Hendrik, nice comments :-)
Do you think block and time out are contradict to each other?

>
> >         print 'get', data_queue.qsize()
> >         draw_canvas(board, canvas_b, x, y, block_width, block_height)
> >         time.sleep(0.3)
>
> this will make the gui unresponsive for the time
>
> >     ##canvas_b.after(300, lambda:draw_canvas_loop(canvas_b))
>
> and then the control runs off the end of the function.
>
> > So, can I use time.sleep() in GUI application? Or Tkinter scheduler
> > just ignore the sleep() function?
>
> time.sleep(sleep_time) will effectively suspend the gui mainloop
> (if it is in the mainloop) for the sleep_time, making the gui unresponsive
> for that time.  Eschew it here.  Use it in other, non GUI helper threads.

Although I don't understand your explaination very well(I guess
maybe .after() re-schedule is better than .sleep unresponsive in GUI
application?)I will take it as a golden rule.

>
>
>
> > And if I use after(), will the code form a recursive function call,
>
> only if it is coded that way - yours does not look recursive to me
>
> > and the memory usage will boost as the program goes (I have watched
> > the task manager in WinXP and find the python.exe eat more and more
> > memory...).
> > def draw_canvas_loop(canvas_b):
> >     board = data_queue.get(block = True, timeout=1)
> >     print 'get', data_queue.qsize()
> >     draw_canvas(board, canvas_b, x, y, block_width, block_height)
>
> Here you draw a new canvas object - what has happened to the
> previous one? Is it possibly still hanging around? Should you
> do something about it?

Yeah, I forgot to *delete* the rectangle object I generate before.
One more question, besides create/delete method, can I just create two
rectangles (one black/one white), and assign two tags to these two
rectangles, and place rectangle by just using tags(that is, can I
place one object on several places of the canvas)?

>
> - Hendrik

--
http://mail.python.org/mailman/listinfo/python-list


Pass same parameter in Recursive function

2008-09-02 Thread Davy
Hi all,

Sometimes I need to pass same parameter in recursive function. From my
point of view, the style is redundant, and I don't what to use some
global style like self.A, self.B, Is there any other choice?

For example,

def func(self, x, y, A, B, C):
  #x, y change in recursive call
  #A, B, C change in the first layer function call, but did not change
in recursive call
  if (...):
func(x, y, A, B, C)
  else(...):
func(x, y, A, B, C)

Best regards,
Davy
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pass same parameter in Recursive function

2008-09-02 Thread Davy
On Sep 3, 11:57 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> Assuming the function is tail-recursive or the "unchanging" arguments
> are immutable, just use a closure:
[SNIP]
Hi Chris,

Thank you :)
Perhaps I should clarify the problem.
1. the function is NOT tail-recursive
2. Yes, the arguments are immutable after I call the function the
first time.

I think the best description of the problem may be:
How to keep some argument constant and accessable in one function
(especially, recursive function). We know that we can use something
like self.parameter to keep the parameter constant and accessable in
one class.

>
> def func(self, x, y, A, B, C):
>     def _func(x,y):
>         return _func(g(A,B,C,x), h(A,B,C,y)) #recurse
>     return _func(x, y)
>
> I'm unsure as to the performance impact of this though.
>
> - Chris
>
>
>
>
>
> On Tue, Sep 2, 2008 at 8:20 PM, Davy <[EMAIL PROTECTED]> wrote:
> > Hi all,
>
> > Sometimes I need to pass same parameter in recursive function. From my
> > point of view, the style is redundant, and I don't what to use some
> > global style like self.A, self.B, Is there any other choice?
>
> > For example,
>
> > def func(self, x, y, A, B, C):
> >  #x, y change in recursive call
> >  #A, B, C change in the first layer function call, but did not change
> > in recursive call
> >  if (...):
> >    func(x, y, A, B, C)
> >  else(...):
> >    func(x, y, A, B, C)
>
> > Best regards,
> > Davy
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> Follow the path of the Iguana...http://rebertia.com- Hide quoted text -
>
> - Show quoted text -

--
http://mail.python.org/mailman/listinfo/python-list


Python/IDLE - text in different colours

2005-06-28 Thread Bill Davy
To make life easier for my users, I'd like to colour my prompt string (as 
handed to raw_input()) a different colour to that produced by print.  I'm 
using Python 2.4.1 and IDLE 1.1.1 on Windows XP.  Is it possible, and if so, 
how?
tia,
Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/IDLE - text in different colours

2005-06-29 Thread Bill Davy
Thank you Nathan, but that does not quite address my question.  I want to 
have code in Python so

make_the_prompt_string(Red)
make_print_output(Green)
while True:
s = raw_input("This prompt (which is really several lines long) will be 
in red: ")
Foo(s)
print "And the result is in Green so the user can see it"

"Nathan Pinno" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
>
>  Bill.
>
>  The way is the click on view, then click script checker, or something 
> like
> that. It will color code the text for you.
>
>  Nathan
>  "Bill Davy" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>  > To make life easier for my users, I'd like to colour my prompt string
> (as
>  > handed to raw_input()) a different colour to that produced by print.
> I'm
>  > using Python 2.4.1 and IDLE 1.1.1 on Windows XP.  Is it possible, and 
> if
> so,
>  > how?
>  > tia,
>  > Bill
>  >
>  >
>
>
>
> -- 
>
>
> 
> Posted via UsenetRevolution.com - Revolutionary Usenet
> ** HIGH RETENTION ** Specializing in Large Binaries Downloads **
> http://www.UsenetRevolution.com 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/IDLE - text in different colours

2005-06-29 Thread Bill Davy
OK, I (sort of) tried that.  Used chr() to avoid issues of which editor and 
rant the following:

import sys

ESC = chr(27)
DarkRed = ESC + "[31;2m"
ResetColour = ESC + "[0m"

print "Initial colour"

sys.stdout.write(DarkRed) ; sys.stdout.flush()

print "Is this dark red?"

sys.stdout.write(ResetColour) ; sys.stdout.flush()

print "Final colour"

The output (in blue, using IDLE) was:

Initial colour
Is this dark red?
Final colour

So, have I missed soemthing?  By the way, in the output there is a little 
square box before the [ in the last two lines.  Does the window Idle sets up 
emulate VT100?

Hey ho, but many thanks.  My user will just have to strain his eyes.
Bill

PS Thanks for the URL.  Interesting.


"TouTaTis" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Bill Davy" <[EMAIL PROTECTED]> wrote in
> news:[EMAIL PROTECTED]:
>
>> To make life easier for my users, I'd like to colour my prompt string
>> (as handed to raw_input()) a different colour to that produced by
>> print.  I'm using Python 2.4.1 and IDLE 1.1.1 on Windows XP.  Is it
>> possible, and if so, how?
>> tia,
>> Bill
>>
>>
>
> Communicating with a Program
>
> Say we want the shell to distinguish more clearly, the output of external
> programs from the input prompt, the commands, and the shell feedback. We
> want the output of external programs to be indented and displayed in a
> different colour than the other text.
>
> Setting the colour of the text is fairly easy using ANSI terminal escape
> sequences. For instance, to set the text colour to dark red, write "
> [31;2m" to the terminal (where  is the escape code - in emacs use
> "C-q ESC" to write ). We can reset the output colour using "
> 0m".
>
> Printing the output of external programs in dark red, we can do using the
> execute() function:
>
> def runCommand(command):
>print 'Running:', command
>
># set output colour:
>sys.stdout.write("[31;2m") ; sys.stdout.flush()
>
>os.system(command)
>
># reset output colour
>sys.stdout.write("[0m")
>
> (Here we need to flush the stdout file to make sure that the escape code
> is written to the terminal before the output of the program)
>
> http://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/process-management.html
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


(Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-18 Thread Bill Davy
I downlaoded and installed 
http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi

I'm trying to build an extension using SWIG 1.3.24 and the linker needs
python24_d.lib (I do not have the DLL either).  I've not found it in any of 
the
downloads.

So I tried to download the source to build it myself.  Of
http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tar.bz2 and
http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz, WinZip (9.0 SR1)
just says "Error reading header after processing 0 entries".

Additionally, I've had no joy downloading the unzipper
(ftp://sources.redhat.com/pub/bzip2/v102/bzip2-102-x86-win32.exe) from the
site cited for the unzipper (http://sources.redhat.com/bzip2/).  It flashed 
up a
black console window momentarily.

Oh, this is so frustrating! :-(

Can anyone point me in the right direction?

And then I can get to grips with my work.

tia
Bill


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-18 Thread Bill Davy

"A.B., Khalid" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> I downlaoded and installed
>> http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi
>>
>> I'm trying to build an extension using SWIG 1.3.24 and the linker
> needs
>> python24_d.lib (I do not have the DLL either).  I've not found it in
> any of
>> the
>> downloads.

> I am no expert in MSVC6, but it sounds like maybe you need to supply
> the no-debug switch in your extention setup.py file: /d NDEBUG.
>
> In case that does not work and help on this is not forthcoming, you can
> always try pyMinGW[1].
>
>
> Regards,
> Khalid


Hmm, that's one possibility but I really do need to keep the debugger 
version going.  I'm only just getting started.  Any other suggestions? 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-19 Thread Bill Davy
Hi,
Many thanks for this.
I am constrained to use MSVC6 (customer) but will look to see if I can run 
VC7.1 alongside VC6.
However, I am still unable to decompress/unpack the downloaded source files 
even with their extensions amended.
Am I really the only person having this difficulty?
Hey ho,
Bill

"James Carroll" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hi Bill,

Python 2.4 requires VC7.1 I just ran into this recently.  Once I
installed VC7.1, I could easily compile the Python source to create a
debug lib.

Winzip should be able to read the python source tarball... There is
one trick though.  Once you download it, it might get renamed to
python.tar.gz.tar  and the trick is to rename the file's extension to
.tar.gz or (my preference)  .tgz.

If it really is a bzip2 file, then you'll need some sort of bunzip.  I
use the cygnus version, but I don't remember having to do anything out
of the way for the python source.

-Jim

On 4/18/05, Bill Davy <[EMAIL PROTECTED]> wrote:
>
> "A.B., Khalid" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Bill Davy wrote:
> >> I downlaoded and installed
> >> http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi
> >>
> >> I'm trying to build an extension using SWIG 1.3.24 and the linker
> > needs
> >> python24_d.lib (I do not have the DLL either).  I've not found it in
> > any of
> >> the
> >> downloads.
>
> > I am no expert in MSVC6, but it sounds like maybe you need to supply
> > the no-debug switch in your extention setup.py file: /d NDEBUG.
> >
> > In case that does not work and help on this is not forthcoming, you can
> > always try pyMinGW[1].
> >
> >
> > Regards,
> > Khalid
>
> Hmm, that's one possibility but I really do need to keep the debugger
> version going.  I'm only just getting started.  Any other suggestions?
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


RE: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-19 Thread Bill Davy
Hi Jim,
I'm not sure that it would be the complete answer, but could you zip me
python24_d.(lib/dll/exp) ?
We are not on VC7.1 (our customer has a mountain of legacy code) and I do
not want to be incompatible with them.  I will see if I can run MSVC6
alongside VC7.1 but have to put customer compatibility firts (I have tried
to edge them on but without success).
Many thanks
Bill

-Original Message-
From: James Carroll [mailto:[EMAIL PROTECTED] 
Sent: 18 April 2005 18:10
To: Bill Davy; python-list@python.org
Subject: Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip
barfs on Python-2.4.1.tar, cannot download bzip2

Hi Bill,

Python 2.4 requires VC7.1 I just ran into this recently.  Once I
installed VC7.1, I could easily compile the Python source to create a
debug lib.

Winzip should be able to read the python source tarball... There is
one trick though.  Once you download it, it might get renamed to
python.tar.gz.tar  and the trick is to rename the file's extension to
tar.gz or (my preference)  .tgz.

If it really is a bzip2 file, then you'll need some sort of bunzip.  I
use the cygnus version, but I don't remember having to do anything out
of the way for the python source.

-Jim

On 4/18/05, Bill Davy <[EMAIL PROTECTED]> wrote:
> 
> "A.B., Khalid" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Bill Davy wrote:
> >> I downlaoded and installed
> >> http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi
> >>
> >> I'm trying to build an extension using SWIG 1.3.24 and the linker
> > needs
> >> python24_d.lib (I do not have the DLL either).  I've not found it in
> > any of
> >> the
> >> downloads.
> 
> > I am no expert in MSVC6, but it sounds like maybe you need to supply
> > the no-debug switch in your extention setup.py file: /d NDEBUG.
> >
> > In case that does not work and help on this is not forthcoming, you can
> > always try pyMinGW[1].
> >
> >
> > Regards,
> > Khalid
> 
> Hmm, that's one possibility but I really do need to keep the debugger
> version going.  I'm only just getting started.  Any other suggestions?
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-20 Thread Bill Davy
Thank you Khalid,



OK.  (4) (compile using MSVC6) worked.



Now working through various issues to do with paths and naming (_d suffix to 
root for DEBUG, _ prefix to root for SWIG, and I had not spotted that SWIG 
makes Module.py that imports _Module.pyd but not _Module_d.pyd for DEBUG 
builds).



I'd like to persuade IDLE to use my locally compiled version of Python 
rather than the one I downloaded, and will find out how eventually. 
Necessary to keep to a VC6 build of 2.4.1 throughout.



Rgds,

Bill (an inveterate top poster, I'm afraid).


"A.B., Khalid" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Okay, let me have another stap at this.
>
> As you have probably noticed MSVC6 is no longer actively supported as
> far as Python 2.4 goes. The official distribution of Python 2.4 for
> Windows is built using MSVC7.1 (or whatever you wish to call it).
>
> We are told that building C extensions with MSVC6 for use in the
> official Python 2.4 (which uses the MSVCR71) is not safe, and mixing
> the different runtime libraries that your extension (or my extension)
> with that which official Python 2.4 uses will/might cause crashes.
> Google around for details on this.
>
> So, what to do? You seem to have four options.
>
> 1. Get and use the MSVC7.1 compiler.
> 2. Get and use the freely distributed MS compiler.
> 3. Download the Python source[1] and compile it yourself in MSVC6
> (there are project files in the source to enable you to do that). Then
> use your MSVC6 to create the extension.
> 4. Get and use MinGW and pyMinGW[2]
>
>
>
>
> Regards,
> Khalid
>
>
>
>
> [1] Check to see if your archiever tool is working, or get the source
> from CVS.
>
> [2] pyMinGW:
> http://jove.prohosting.com/iwave/ipython/pyMinGW.html
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-20 Thread Bill Davy
Thanks Jaime,

I'm making gradual progress and am finding it quite satisfying.  Resorted to 
tracing Python in MSVC6 to see what it was trying to IMPORT, which is a bit 
heavy but thank heavens for the sources.

Had not thouight of "adapting" SWIG, and will think about it when I have a 
clearer view of what I am doing (rather deeply embedded at present, trying 
to get one success).  I had not spotted SWIG's wrapper round a wrapper 
(Module.py imports _Module.pyd) but it's reasonable except they go into 
different directories.  And there's the _d too, of course :-(

Many thanks for your help,

Bill

"Jaime Wyant" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
I fight the python24_d.lib problem with swig daily.  The way I got
around it was to modify swig's python configuration module.  Mine was
located at

/lib/swig1.3/python/python.swg

(I'm using cygwin)

At the top, I changed

#include "python.h"

to

#ifdef _DEBUG
  #undef _DEBUG
  #include "python.h"
  #define _DEBUG
#else
  #include "python.h"
#endif

Somewhere in the includes, python uses a pragma telling the MSVC
compiler which library to link the object files against.  Because
you're building a _DEBUG build, you magically get the python24_d.lib
library.

hth,
jw

On 4/18/05, Bill Davy <[EMAIL PROTECTED]> wrote:
> I downlaoded and installed
> http://www.python.org/ftp/python/2.4.1/python-2.4.1.msi
>
> I'm trying to build an extension using SWIG 1.3.24 and the linker needs
> python24_d.lib (I do not have the DLL either).  I've not found it in any 
> of
> the
> downloads.
>
> So I tried to download the source to build it myself.  Of
> http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tar.bz2 and
> http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz, WinZip (9.0 SR1)
> just says "Error reading header after processing 0 entries".
>
> Additionally, I've had no joy downloading the unzipper
> (ftp://sources.redhat.com/pub/bzip2/v102/bzip2-102-x86-win32.exe) from the
> site cited for the unzipper (http://sources.redhat.com/bzip2/).  It 
> flashed
> up a
> black console window momentarily.
>
> Oh, this is so frustrating! :-(
>
> Can anyone point me in the right direction?
>
> And then I can get to grips with my work.
>
> tia
> Bill
>
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-21 Thread Bill Davy
Hi Scott,
Nice idea.  Tried that but no more information about where the file was 
(not) found (see below).
But many thanks for a useful flag.  I did not see them in the documentation. 
What should I be lkooking for? [StopPres: Ah ha -h why did I not think of 
that?]
Bill

# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# C:\Python24\lib\site.pyc matches C:\Python24\lib\site.py
import site # precompiled from C:\Python24\lib\site.pyc
# C:\Python24\lib\os.pyc matches C:\Python24\lib\os.py
import os # precompiled from C:\Python24\lib\os.pyc
import nt # builtin
# C:\Python24\lib\ntpath.pyc matches C:\Python24\lib\ntpath.py
import ntpath # precompiled from C:\Python24\lib\ntpath.pyc
# C:\Python24\lib\stat.pyc matches C:\Python24\lib\stat.py
import stat # precompiled from C:\Python24\lib\stat.pyc
# C:\Python24\lib\UserDict.pyc matches C:\Python24\lib\UserDict.py
import UserDict # precompiled from C:\Python24\lib\UserDict.pyc
# C:\Python24\lib\copy_reg.pyc matches C:\Python24\lib\copy_reg.py
import copy_reg # precompiled from C:\Python24\lib\copy_reg.pyc
# C:\Python24\lib\types.pyc matches C:\Python24\lib\types.py
import types # precompiled from C:\Python24\lib\types.pyc
# C:\Python24\lib\locale.pyc matches C:\Python24\lib\locale.py
import locale # precompiled from C:\Python24\lib\locale.pyc
import _locale # builtin
# C:\Python24\lib\codecs.pyc matches C:\Python24\lib\codecs.py
import codecs # precompiled from C:\Python24\lib\codecs.pyc
import _codecs # builtin
import encodings # directory C:\Python24\lib\encodings
# C:\Python24\lib\encodings\__init__.pyc matches 
C:\Python24\lib\encodings\__ini
t__.py
import encodings # precompiled from C:\Python24\lib\encodings\__init__.pyc
# C:\Python24\lib\encodings\aliases.pyc matches 
C:\Python24\lib\encodings\aliase
s.py
import encodings.aliases # precompiled from 
C:\Python24\lib\encodings\aliases.py
c
# C:\Python24\lib\encodings\cp1252.pyc matches 
C:\Python24\lib\encodings\cp1252.
py
import encodings.cp1252 # precompiled from 
C:\Python24\lib\encodings\cp1252.pyc
# C:\Python24\lib\warnings.pyc matches C:\Python24\lib\warnings.py
import warnings # precompiled from C:\Python24\lib\warnings.pyc
# C:\Python24\lib\linecache.pyc matches C:\Python24\lib\linecache.py
import linecache # precompiled from C:\Python24\lib\linecache.pyc
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
# C:\Python24\lib\encodings\cp850.pyc matches 
C:\Python24\lib\encodings\cp850.py

import encodings.cp850 # precompiled from 
C:\Python24\lib\encodings\cp850.pyc
>>> import SHIP
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named SHIP
>>> import SHIP_d
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named SHIP_d
>>> import _SHIP
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named _SHIP
>>> import _SHIP_d
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: DLL load failed: The specified module could not be found.
>>> _SHIP_d
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name '_SHIP_d' is not defined
>>>
"Scott David Daniels" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> Thanks Jaime,
>>
>> I'm making gradual progress and am finding it quite satisfying.  Resorted 
>> to tracing Python in MSVC6 to see what it was trying to IMPORT, which is 
>> a bit heavy but thank heavens for the sources.
> You might try running python from a command window and running it "-v" as 
> in:
>
> python -v prog.py -args ...
>
> --Scott David Daniels
> [EMAIL PROTECTED] 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (Python newbie) Using XP-SP2/MSVC6: No Python24_d.lib, winzip barfs on Python-2.4.1.tar, cannot download bzip2

2005-04-22 Thread Bill Davy
> Traceback (most recent call last):
>>   File "", line 1, in ?
>> ImportError: No module named SHIP
>>
> Two common problems here:
> 1) There is no file *\SHIP.pyd where * is one entry of sys.path
> 2) The capitalization is not correct.  The file lookup will succeed,
>but then, when "initSHIP(void)" is hunted for in the module, no such
>function will be found.  It is kind of surprising to get the funny
>mix of case-sensitivity and case-insensitivity that results from
>mixing Python and Windows.  By the way, I might not even have it
>right here; I simply make everything as if all tests were case-
>sensitive.
>
> --Scott David Daniels
> [EMAIL PROTECTED]

And also Python may be looking for SHIP_d.pyd too (as it is Windows Debug 
version).

Anyway, I am making prgress (but see new thread on IDLE)

Thanks for the help.

Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE: How to point it to the Python executables I want it to see on Windows

2005-04-22 Thread Bill Davy
Assuming they run as a separate thread, I want to point IDLE to 
.../Debug/Python_d.exe one day and .../Release/Python.exe for the next.
Also, is there any easy way to run the .../Debug/Python_d.exe so started 
under the MSVC debugger?
tia,
Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list


SWIG/Python2.4.1: "ImportError: dynamic module does not define init function (initSHIP)"

2005-05-04 Thread Bill Davy
Hello,

I am using SWIG-1.3.24 to make an extension (called SHIP) to Python2.4.1 and 
then running under IDLE (if that makes any difference) but when I "import 
SHIP" I get:

>>> import SHIP

Traceback (most recent call last):
  File "", line 1, in -toplevel-
import SHIP
ImportError: dynamic module does not define init function (initSHIP)
>>>

Indeed, SHIP.py does not define an initSHIP.  It does have "import _SHIP"

SHIP_wrap.cpp (produced by SWIG) does have init_SHIP (defined to SWIG_init).

It seems to me I should not be editing SHIP.py (as made by SWIG) but it does 
seem to be missing something, or am I?

Thanks in advance,

   Bill

PS I gave up trying to use IDLE with a locally compiled debug version of 
Python - that's for another day (or week), but thanks for the assorted help 
I was given. 


-- 
http://mail.python.org/mailman/listinfo/python-list


SWIG/IDLE/Python: F5 SHIP.py works but "import SHIP" gives "ImportError: dynamic module does not define init function (initSHIP)"

2005-05-12 Thread Bill Davy
I am working with MSVC6 on Windows XP.

I have created an MSVC project called SHIP

I have a file SHIP.i with "%module SHIP" as the first line (file is below).

I run SHIP.i through SWIG 1.3.24 to obtain SHIP_wrap.cpp and SHIP.py; the 
latter contains the line "import _SHIP".

I compile SHIP_wrap.cpp and a bunch of files into a DLL which I have the 
linker place in _SHIP.pyd and all goes well.

I start IDLE (version 1.1.1, with Python 2.4.1)

If I open SHIP.py in an edit window and run it (using F5) it runs and if I 
do >>> _SHIP.__dict__.keys() I get a load of function names which are like 
the ones I'd expect (new_BallScrew for example, where BallScrew is one of my 
classes [and is the interface class to the thing I am really interested in 
which is already called BallScrewC, before you ask]).

Then I can do things like:

>>> bs = BallScrew(0)

>>> bs.Stop()

>>> del bs

They work fine. Except of course I really want to put all that stuff in a 
script, say test1.py:

import SHIP # This is where my problems begin.

bs = BallScrew(0)

bs.GotoLimit(1)

bs.Stop()

del bs

Which I do and when I run test1.py using F5, the line "import SHIP" in 
test1.py produces:

ImportError: dynamic module does not define init function (initSHIP)

So, why can I run SHIP.py straight into Python using F5 but not import it 
either directly (>>> import SHIP gives the same error) or indirectly when I 
am running another file?

One way round this (though I would like to solve this problem as it will 
make things easier as the application grows) is for F5 in IDLE not to 
restart the Python interpreter.

My aim is for an engineer to be able to use IDLE to write programs to test 
hardware without having to learn C++ to access my OO interface. IDLE and 
Python are ideal but I want to make it easy for them to load the interface 
(i.e. SHIP) between Python and my OO interface.

Many thanks in advance for any helpful suggestions,

Bill

PS I posted this to [EMAIL PROTECTED] but it did not seem to get through.



SHIP.i:

%module SHIP

%{

#include "SHIPIF.hpp"

%}

%include "SHIPIF.hpp"



SHIP.py (with no initSHIP L ):

# This file was created automatically by SWIG.

# Don't modify this file, modify the SWIG interface instead.

# This file is compatible with both classic and new-style classes.

import _SHIP

def _swig_setattr_nondynamic(self,class_type,name,value,static=1):

if (name == "this"):

if isinstance(value, class_type):

self.__dict__[name] = value.this

if hasattr(value,"thisown"): self.__dict__["thisown"] = value.thisown

del value.thisown

return

method = class_type.__swig_setmethods__.get(name,None)

if method: return method(self,value)

if (not static) or hasattr(self,name) or (name == "thisown"):

self.__dict__[name] = value

else:

raise AttributeError("You cannot add attributes to %s" % self)

def _swig_setattr(self,class_type,name,value):

return _swig_setattr_nondynamic(self,class_type,name,value,0)

def _swig_getattr(self,class_type,name):

method = class_type.__swig_getmethods__.get(name,None)

if method: return method(self)

raise AttributeError,name

import types

try:

_object = types.ObjectType

_newclass = 1

except AttributeError:

class _object : pass

_newclass = 0

del types





ToString = _SHIP.ToString

class ObjectCounterC(_object):

__swig_setmethods__ = {}

__setattr__ = lambda self, name, value: _swig_setattr(self, ObjectCounterC, 
name, value)

__swig_getmethods__ = {}

__getattr__ = lambda self, name: _swig_getattr(self, ObjectCounterC, name)

def __repr__(self):

return "<%s.%s; proxy of C++ ObjectCounterC instance at %s>" % 
(self.__class__.__module__, self.__class__.__name__, self.this,)

def __init__(self, *args):

_swig_setattr(self, ObjectCounterC, 'this', _SHIP.new_ObjectCounterC(*args))

_swig_setattr(self, ObjectCounterC, 'thisown', 1)

def __del__(self, destroy=_SHIP.delete_ObjectCounterC):

try:

if self.thisown: destroy(self)

except: pass



class ObjectCounterCPtr(ObjectCounterC):

def __init__(self, this):

_swig_setattr(self, ObjectCounterC, 'this', this)

if not hasattr(self,"thisown"): _swig_setattr(self, ObjectCounterC, 
'thisown', 0)

_swig_setattr(self, ObjectCounterC,self.__class__,ObjectCounterC)

_SHIP.ObjectCounterC_swigregister(ObjectCounterCPtr)

class CallBack(_object):

__swig_setmethods__ = {}

__setattr__ = lambda self, name, value: _swig_setattr(self, CallBack, name, 
value)

__swig_getmethods__ = {}

__getattr__ = lambda self, name: _swig_getattr(self, CallBack, name)

def __repr__(self):

return "<%s.%s; proxy of C++ CallBack instance at %s>" % 
(self.__class__.__module__, self.__class__.__name__, self.this,)

def __init__(self, *args):

_swig_setattr(self, CallBack, 'this', _SHIP.new_CallBack(*args))

_swig_setattr(self, CallBack, 'thisown', 1)

def __del__(self, destroy=_SHIP.delete_CallBack):

try:

if self.thisown: destroy(self)

except: pass

def S

DLL load failed: The specified procedure could not be found

2005-05-31 Thread Bill Davy
sys.path:
 H:\Husky\HostPC\V1\SHIP\Debug
 H:\Husky\HostPC\V1\SHIP
 E:\Bill\Python-2.4.1\PCbuild\python24_d.zip
 C:\Python24\Lib
 C:\Python24\DLLs
 C:\Python24\Lib\lib-tk
 H:\Husky\HostPC\V1\RunSHIP
 H:\Husky\HostPC\V1\Debug
 C:\Python24
 C:\Python24\lib\site-packages

Traceback (most recent call last):
  File "H:\Husky\HostPC\V1\SHIP\test1.py", line 7, in ?
import SHIP
  File "H:\Husky\HostPC\V1\Debug\SHIP.py", line 5, in ?
import _SHIP
ImportError: DLL load failed: The specified procedure could not be found.

a) What "specified procedure "
b) SHIP was made by SWIG
c) Is there some way to find out which DLL and which procedure is involved?

It's all debug build, sys.path has all the Debug directories.

tia
Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DLL load failed: The specified procedure could not be found

2005-06-01 Thread Bill Davy
"John Machin" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

>> a) What "specified procedure "
>> b) SHIP was made by SWIG
>
> and so presumably was _SHIP ... therefore it appears that you might be 
> better off asking for help on the SWIG mailing list.

I will too.

>
>> c) Is there some way to find out which DLL and which procedure is 
>> involved?
>
> One would expect given the reported context (import _SHIP) that it has 
> found (somewhere!) a DLL called "_SHIP.pyd" and is looking in it 
> (unsuccessfully) for an entrypoint called "init_SHIP".
>
> The usual suspect here would be the C (or C++) compiler messing with the 
> name of the entrypoint; possible messes include underscores at the front 
> and/or frame size at the end e.g. "[EMAIL PROTECTED]" instead of just 
> "initfoo". 
> Possibly you are using a C[++] compiler that's not the one that SWIG 
> thinks you are using.
>
> But exactly which DLL? Given your "interesting" sys.path, it might be an 
> idea to run python with the -v argument, so you can see where all your 
> imports are resolved.

I've not been able to find where sys.path finds its components and would 
happily sort them out.  It does not seem to be PYTHONPATH or PATH or 
PYTHON_LIB.

I had to make Python as I wanted a debug build for Win32 (and hence 
E:\Bill\Python-2.4.1\PCbuild\python24_d.zip on sys.path though why the zip I 
have no idea).  I have discovered the symbol __debug__ is True for debug 
builds.

>
> Once you have worked out which _SHIP.pyd is the cause, you can inspect it 
> and determine what entrypoint(s) it has.
>
> HTH,
> John

Dear John (and all)

That's a great help, really.  A simple thing like reminding me of -v (give a 
man a fish, etc) will help now and hereafter.

So, now we can see what Python is trying to do:

Python 2.4.1 (#65, May 24 2005, 11:31:45) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
# trying H:\Husky\HostPC\V1\SHIP\Debug\SHIP_d.pyd
# trying H:\Husky\HostPC\V1\SHIP\Debug\SHIP_d.dll
# trying H:\Husky\HostPC\V1\SHIP\Debug\SHIP.py
# H:\Husky\HostPC\V1\SHIP\Debug\SHIP.pyc matches 
H:\Husky\HostPC\V1\SHIP\Debug\SHIP.py
import SHIP # precompiled from H:\Husky\HostPC\V1\SHIP\Debug\SHIP.pyc
# trying H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd
#   clear[2] __name__
#   clear[2] __file__
Traceback (most recent call last):
  File "H:\Husky\HostPC\V1\SHIP\test1.py", line 15, in ?
import SHIP
  File "H:\Husky\HostPC\V1\SHIP\Debug\SHIP.py", line 5, in ?
import _SHIP
ImportError: DLL load failed: The specified procedure could not be found.
# clear __builtin__._

It's still not clear what procedure could not be found (surely not 
__file__?!).  However, the output from "dumpbin /exports 
H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd" is:

H:\Husky\HostPC\V1\SHIP\Debug>dumpbin /exports 
H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd
Microsoft (R) COFF Binary File Dumper Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.


Dump of file H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd

File Type: DLL

  Section contains the following exports for SHIP.pyd

   0 characteristics
429D76E4 time date stamp Wed Jun 01 09:50:44 2005
0.00 version
   1 ordinal base
   1 number of functions
   1 number of names

ordinal hint RVA  name

  10 1096 init_SHIP

  Summary

6000 .data
2000 .idata
3000 .rdata
2000 .reloc
1000 .rsrc
   2 .text

So _SHIP_d.pyd does export init_SHIP.

The odd thing there (to me) is the reference to "SHIP.pyd".  Is that coming 
from SHIP.def which has:
LIBRARY  "SHIP"

The thing that is really bugging me is that this was all working before the 
weekend :-(

I am also posting this to the SWIG mailing list as suggested.

TIA

Bill


-- 
http://mail.python.org/mailman/listinfo/python-list


Python equivt of __FILE__ and __LINE__

2008-02-11 Thread Bill Davy
Writing a quick and dirty assembler and want to give the user the location 
of an error.  The "assembly language" is Python.  If the user wants to 
generat some object code they write something  like:

Label(LoopLable)
Load(R4)
Dec()
JNZ(LoopLabel)

I can use Python to do all the expression evalutaion, conversion from Python 
FP to target FP, include files, macros (done as function definitions).  The 
functions like Load() generate the approproyte object code.

So, for example, when a label is defined or referenced, I save the File,Line 
so if there is not exactly one defintion or no references, I can report the 
file location(s) to be considered.  In the example, I would want to report 
that LoopLable is not referenced, and LoopLabel is not defined.

TIA,
Bill

PS www.SynectixLtd.com is not relevant 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivt of __FILE__ and __LINE__

2008-02-12 Thread Bill Davy
"thebjorn" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Feb 11, 4:55 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
>> Bill Davy wrote:
>> > Writing a quick and dirty assembler and want to give the user the 
>> > location
>> > of an error.  The "assembly language" is Python.  If the user wants to
>> > generat some object code they write something  like:
>>
>> > Label(LoopLable)
>> > Load(R4)
>> > Dec()
>> > JNZ(LoopLabel)
>>
>> > I can use Python to do all the expression evalutaion, conversion from 
>> > Python
>> > FP to target FP, include files, macros (done as function definitions). 
>> > The
>> > functions like Load() generate the approproyte object code.
>>
>> > So, for example, when a label is defined or referenced, I save the 
>> > File,Line
>> > so if there is not exactly one defintion or no references, I can report 
>> > the
>> > file location(s) to be considered.  In the example, I would want to 
>> > report
>> > that LoopLable is not referenced, and LoopLabel is not defined.
>>
>> > TIA,
>> > Bill
>>
>> >
>>
>> You *can* get at that kind of information: The traceback module has a
>> function called "extract_stack" which can give you a pointer to the
>> whole execution stack.  From that can be generated all the usual stuff
>> you see in a traceback -- including file and line information.  *How*
>> you extract that stuff, I'll leave as an exercises for the reader.
>> (Meaning I haven't a clue.)
>>
>> Gary Herron
>
> I think the inspect module might be more useful... the getfile() and
> getsourcelines() look promising.
>
> -- bjorn


I think I'll go with the tarceback route because if the user defines 
functions to emit code, I can traceback silently from where the error is 
found to the call to Load() or Store() etc, and then trace back visibly, the 
user will get a traceback of their code (and not my implementation details).

But very interesting and nice to know about these functions/modules.  What a 
lovely langauge.

Bill

PS www.SynectixLtd.com is not relevant 


-- 
http://mail.python.org/mailman/listinfo/python-list


Cannot understand error message

2008-02-13 Thread Bill Davy
The following code produces an error message (using Idle with Py 2.4 and 
2.5).  "There's an error in your program: EOL while scanning single-quoted 
string".  It comes just after "s = ''" (put there to try and isolate the 
broken string).

It would be good if the error message pointed me to the start of said single 
quoted string.

The colouring in IDLE does not indicate a bad string.

Puzzled.

Bill


#

# The traceback module is used to provide a stack trace to

# show the user where the error occured.  See Error().

#

import traceback

#

# The math module is used to convert numbers between the Python real format

# and the Keil real format.  See KeilToFloatingPoint() and FloatingToKeil().

#

import math



LOAD_LIT = 1

LOAD_REG = 1

STORE_REG = 1

ADD_LIT_FP = 2 + 8

ADD_LIT_INT = 2 + 16

ADD_REG_FP = 2 + 32

ADD_REG_INT = 9

SUB_LIT_FP = 11

SUB_LIT_INT = 12

SUB_REG_FP = 13

SUB_REG_INT =14

MUL_LIT_FP = 11

MUL_LIT_INT = 12

MUL_REG_FP = 13

MUL_REG_INT =14

DIV_LIT_FP = 11

DIV_LIT_INT = 12

DIV_REG_FP = 13

DIV_REG_INT =14

AND_LIT_INT = 12

AND_REG_INT =14

OR_LIT_INT = 12

OR_REG_INT =14

NEGATE_FP = 11

NEGATE_INT = 12

ABSOLUTE_FP = 13

ABSOLUTE_INT = 14

INVERT_INT = 15

JUMP_OPCODE = 15

JLT_OPCODE = 15

JGT_OPCODE = 15

JLE_OPCODE = 15

JGE_OPCODE = 15

JEQ_OPCODE = 15

JNE_OPCODE = 15



BinaryOps={

"LOAD":{float:{"L":LOAD_LIT,"R":LOAD_REG},int:{"L":LOAD_LIT,"R":LOAD_REG}},

"STORE":{float:{"R":STORE_REG},int:{"R":STORE_REG}},


"ADD":{float:{"L":ADD_LIT_FP,"R":ADD_REG_FP},int:{"L":ADD_LIT_INT,"R":ADD_REG_INT}},


"SUB":{float:{"L":SUB_LIT_FP,"R":SUB_REG_FP},int:{"L":SUB_LIT_INT,"R":SUB_REG_INT}},


"MUL":{float:{"L":MUL_LIT_FP,"R":MUL_REG_FP},int:{"L":MUL_LIT_INT,"R":MUL_REG_INT}},


"DIV":{float:{"L":DIV_LIT_FP,"R":DIV_REG_FP},int:{"L":DIV_LIT_INT,"R":DIV_REG_INT}},

"AND":{int:{"L":AND_LIT_INT,"R":AND_REG_INT}},

"OR":{int:{"L":OR_LIT_INT,"R":OR_REG_INT}}

}

UnaryOps={

"NEGATE":{float:NEGATE_FP, int:NEGATE_INT},

"ABSOLUTE":{float:ABSOLUTE_FP, int:ABSOLUTE_INT},

"INVERT":{int:INVERT_INT}

}



JumpOps={

"JUMP":JUMP_OPCODE,

"JLT":JLT_OPCODE,

"JGT":JGT_OPCODE,

"JLE":JLE_OPCODE,

"JGE":JGE_OPCODE,

"JEQ":JEQ_OPCODE,

"JNE":JNE_OPCODE

}

def IsOpCode(s):

if ( s in BinaryOps ): return True;

if ( s in UnaryOps ): return True;

if ( s in JumpOps ): return True;

return False

class Register:

"""

This class provides us with a register (say) 0..32

In addtion to a number, a register can be given a name.

It allows LOAD(arg) and other opcodes to distinguish between

references to a register and a literal value.

"""

def __init__(self,Id,Name=None):

self.Number = Id

if ( Name == None):

self.Name = "R%d" % Id

else:

self.Name = Name

def RegisterNumber(self):

return self.Number



def RegisterName(self):

return self.Name

R0=Register(0)

R1=Register(1)

R2=Register(2)

Now=Register(2,"Now")

def IsRegister(arg):

return hasattr( arg, "RegisterNumber")

assert not IsRegister(0)

assert not IsRegister(1.2)

assert IsRegister(R1)

assert IsRegister(Now)

#

# ErrorCount is global as it is shared by all slaves.

#

ErrorCount = 0

def Error(Message):

"""

work back through the traceback until you find a function whose name is 
in one of the

opcode dictionaries and trace back from there.  This will keep internal

implemenataion functions private but still allow the suer to define 
functions

that generate code.

"""

global ErrorCount

ErrorCount += 1



"""

[

('', 1, '?', None),

('C:\\Python24\\lib\\idlelib\\run.py', 90, 'main', 'ret = method(*args, 
**kwargs)'),

('C:\\Python24\\lib\\idlelib\\run.py', 283, 'runcode', 'exec code in 
self.locals'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 434, '?', 'STORE(1)'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 147, 'STORE', 
'self.BINOP("STORE",Arg,Msg)'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 198, 'BINOP', 'return 
Error("Cannot perform %s on %s" % (Op,Arg))'),

('H:\\Husky Experiments\\Viper1\\tmp.py', 106, 'Error', 'tb = 
traceback.extract_stack()')

]

"""

tb = traceback.extract_stack()

BeforePrinting = True

IsPrinting = False

for i in range(len(tb)-1,0,-1):

frame = tb[i]

if ( BeforePrinting ):

# Looking to start

if IsOpCode(frame[2]): # start printing

IsPrinting = True

BeforePrinting = False

print "John: %s\nTrace back follows:" % Message

elif ( IsPrinting ):

print '\tFile "%s", line %u, %s' % (frame[0], frame[1], 
frame[3])

# Stop when we find the curious function "?"

if (frame[2] == "?"):

break

if BeforePrinting:

print "John: %s (no trace back)" % Messa

Re: Cannot understand error message

2008-02-14 Thread Bill Davy
"Chris" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> It doesn't like all that text in the previous one...
>
> Just before s = '' you have 4 double quotes to close to doc-string
> instead of 3.


Doh.

I had put in the s = '' to see if I could force IDLE to say something more, 
and perhaps if I had put in "" I would have done better.

Apologies to anyone who imagined I expected them to read 500 lines of my 
novice Python.

Interesting that some colourers work better than others.  It must be quite a 
challenge.

IDLE did not offer a full traceback just a pop-up.  If it had, I would 
either have soved the problem or posted it.  I'm not afraid of long (boring) 
posts.

Many thanks for the help.  Must get a bigger screen and new eyes.

Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot understand error message

2008-02-14 Thread Bill Davy
"Bruno Desthuilliers" <[EMAIL PROTECTED]> 
wrote in message news:[EMAIL PROTECTED]
> Bill Davy a écrit :
> (snip)
>> Doh.
>
> (snip)
>
>> Interesting that some colourers work better than others.  It must be 
>> quite a challenge.
>>
>> IDLE did not offer a full traceback just a pop-up.
>
> Mmm... That sure is bad. Isn't there an option to get a better behaviour?
>
> Anyway, just trying to run your script from the command-line, or import it 
> from the (command-line) Python shell would have get you the full 
> traceback.


Just tried importing it into the Python window of IDLE and I do indeed get a 
caret for the initial (unmatched) '"'.  Something I shall watch out for and 
use in future.
Many thanks.

>
>> If it had, I would either have soved the problem or posted it.  I'm not 
>> afraid of long (boring) posts.
>>
>> Many thanks for the help.  Must get a bigger screen and new eyes.
>
> Or a better code editor.

I just grabbed what was on the shelf.  Is there a Python plug-in for MSVC? 
;-)

Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list

Could anyone give a working example using asynchat in Python3.0?

2008-10-21 Thread davy zhang
I tried to use them but the terminator option seems no effect

I search the google but all the code is Python2.x format, I modified
them but I get no luck.

thanks for any advice
--
http://mail.python.org/mailman/listinfo/python-list


why this server can not run in python30

2008-10-21 Thread davy zhang
import asyncore, asynchat
import os, socket, string

PORT = 8000

class HTTPChannel(asynchat.async_chat):

def __init__(self, server, sock, addr):
asynchat.async_chat.__init__(self, sock)
self.set_terminator("\r\n")
self.request = None
self.data = ""
self.shutdown = 0

def collect_incoming_data(self, data):
self.data = self.data + data

def found_terminator(self):
if not self.request:
# got the request line
self.request = string.split(self.data, None, 2)
if len(self.request) != 3:
self.shutdown = 1
else:
self.push("HTTP/1.0 200 OK\r\n")
self.push("Content-type: text/html\r\n")
self.push("\r\n")
self.data = self.data + "\r\n"
self.set_terminator("\r\n\r\n") # look for end of headers
else:
# return payload.
self.push("\r\n")
self.push(self.data)
self.push("\r\n")
self.close_when_done()

class HTTPServer(asyncore.dispatcher):

def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(("", port))
self.listen(5)

def handle_accept(self):
conn, addr = self.accept()
HTTPChannel(self, conn, addr)

#
# try it out

s = HTTPServer(PORT)
print ("serving at port", PORT, "...")
asyncore.loop()
--
http://mail.python.org/mailman/listinfo/python-list


Re: why this server can not run in python30

2008-10-22 Thread davy zhang
thanks so much for fixing the problems!!


On Wed, Oct 22, 2008 at 2:56 PM, Gabriel Genellina
<[EMAIL PROTECTED]> wrote:
> En Wed, 22 Oct 2008 03:45:31 -0200, davy zhang <[EMAIL PROTECTED]>
> escribió:
>
>> import asyncore, asynchat
>> import os, socket, string
>>
>> PORT = 8000
>>
>> class HTTPChannel(asynchat.async_chat):
>>
>>def __init__(self, server, sock, addr):
>>asynchat.async_chat.__init__(self, sock)
>>self.set_terminator("\r\n")
>
> self.set_terminator(b"\r\n")
>
>>self.request = None
>>self.data = ""
>
> self.data = b""
>
> Same for all remaining string literals, should be bytes instead.
>
>>self.request = string.split(self.data, None, 2)
>
> The string module functions are deprecated ages ago in favor of the
> corresponding string (instance) methods:
>
> self.request = self.data.split(None, 2)
>
> That's enough - the example worked fine for me after doing these changes.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


new to python network programming is async_chat.push thread-safe? python3.0

2008-10-23 Thread davy zhang
I wrote this server to handle incoming messages in a process using
multiprocessing named "handler", and sending message in a Thread named
"sender",  'cause I think the async_chat object can not pass between
processes.

My project is a network gate server with many complex logic handler
behind, so I use multiprocessing to handle them separately and send
back the clients later when done.
To use the server multicore cpu I tried to separate the send and
receive function in different process but it seems can not be done :)

I just get questions about this design:
1. is async_chat.push thread-safe? 'Cause I found random errors
reporting push fifo queue out of index 0 sometimes
2. is the whole design odd in any way?


here is my code

import asyncore, asynchat
import os, socket, string
from multiprocessing import Process,Manager
import pickle
import _thread

PORT = 80

policyRequest = b""
policyReturn = b"""
 
  \x00"""

def handler(taskList,msgList):
while 1:
print('getting task')
item = pickle.loads(taskList.get())
print('item before handle ', item)
item['msg'] += b' hanlded done'
msgList.put(pickle.dumps(item))

def findClient(id):
for item in clients:
if item.idx == id:
return item

def sender():
global msgList
while 1:
item = pickle.loads(msgList.get())
#print time()
c = findClient(item['cid'])
#print time()
c.push(item['msg'])
print('msg sent ',item['msg'])
#print time()

class HTTPChannel(asynchat.async_chat):

def __init__(self, server, sock, addr):
global cid;
asynchat.async_chat.__init__(self, sock)
self.set_terminator(b"\x00")
self.data = b""
cid += 1
self.idx = cid
if not self in clients:
clients.append(self)

def collect_incoming_data(self, data):
self.data = self.data + data
print(data)

def found_terminator(self):
global taskList
print("found",self.data)
if self.data == policyRequest:
self.push(policyReturn)
else:
d = {'cid':self.idx,'msg':self.data}
taskList.put(pickle.dumps(d))
self.data = b""

def handle_close(self):
if self in clients:
clients.remove(self)

class HTTPServer(asyncore.dispatcher):

def __init__(self, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(("", port))
self.listen(5)

def handle_accept(self):
conn, addr = self.accept()
HTTPChannel(self, conn, addr)


#
# try it out
if __name__ == "__main__":
s = HTTPServer(PORT)
print ("serving at port", PORT, "...")

#clients sock obj list stored for further use
clients=[]

#client id auto increasement
cid = 0

manager = Manager()
taskList = manager.Queue()
msgList = manager.Queue()


h = Process(target=handler,args=(taskList,msgList))
h.start()


_thread.start_new_thread(sender,())
print('entering loop')

asyncore.loop()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Will Python 3 be "stackless"?

2008-10-23 Thread davy zhang
multiprocessing is good enough for now,

On Fri, Oct 24, 2008 at 4:30 AM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Phillip B Oldham schrieb:
>>
>> On Thu, Oct 23, 2008 at 9:20 PM, Chris Rebert <[EMAIL PROTECTED]> wrote:
>>>
>>> No, it will definitely not.
>>
>>> From your statement (and I'm terribly sorry if I've taken it out of
>>
>> context) it would seem that such features are frowned-upon. Is this
>> correct? And if so, why?
>
> You got the wrong impression. It's not frowned upon. It just is a lot of
> extra effort to implemnt & thus makes the development of "normal" features
> more complex.
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


why asynchat's initiate_send() get called twice after reconnect ?

2008-10-25 Thread davy zhang
Python3.0rc1  windowsxp

in the lib\asynchat.py

   def handle_write (self):
   self.initiate_send()

   def push (self, data):
   sabs = self.ac_out_buffer_size
   if len(data) > sabs:
   for i in range(0, len(data), sabs):
   self.producer_fifo.append(data[i:i+sabs])
   else:
   self.producer_fifo.append(data)
   self.initiate_send()

when there's only one time connection, the object works just fine. but
problems came out when the client disconnected and reconnected again
to the server, it seems there are two ways to call the initiate_send,
one is from push() which I called in my program, one is from
handle_write() which automatically called in asyncore.loop(). I just
can't get it why one time connection works fine but multi-time
connection went bad.

I printed the traceback. I found when one time connection made, the
handle_write() always get silent, but when the second time, it get
called and start to call initiate_send in the same time as push()  get
called. So confusing



So I tried to remove the initiate_send from push() and the code
magically works fine for me.

the main program lists below:
since it's need a flash client, I attached a webpage to reproduce the problem
click on the connect button multiple times and clicked on the send
button will make an error

import asyncore, asynchat
import os, socket, string
from multiprocessing import Process,Manager
import pickle
import _thread
import threading

PORT = 80

policyRequest = b""
policyReturn = b"""

 \x00"""

def handler(taskList,msgList):
   while 1:
   print('getting task')
   item = pickle.loads(taskList.get())
   print('item before handle ', item)
   #do something
   item['msg'] += b' hanlded done'
   msgList.put(pickle.dumps(item))

def findClient(id):
   for item in clients:
   if item.idx == id:
   return item

def pushData(ch,data):
   global pushLock
   pushLock.acquire()
   try:
   ch.push(data)
   finally:
   pushLock.release()


def sender():
   global msgList
   print('thread started')
   while 1:
   item = pickle.loads(msgList.get())
   #print time()
   c = findClient(item['cid'])
   #print time()
   #wrong here it's not thread safe, need some wrapper
   #c.push(item['msg'])
   pushData(c,item['msg'])
   print('msg sent ',item['msg'])
   #print time()

class HTTPChannel(asynchat.async_chat):

   def __init__(self, server, sock, addr):
   global cid;
   asynchat.async_chat.__init__(self, sock)
   self.set_terminator(b"\x00")
   self.data = b""
   cid += 1
   self.idx = cid
   if not self in clients:
   print('add to clients:',self)
   clients.append(self)

   def collect_incoming_data(self, data):
   self.data = self.data + data
   print(data)

   def found_terminator(self):
   global taskList
   print("found",self.data)
   if self.data == policyRequest:
   pushData(self,policyReturn)
   self.close_when_done()
   else:
   d = {'cid':self.idx,'msg':self.data}
   taskList.put(pickle.dumps(d))
   self.data = b""

   def handle_close(self):
   if self in clients:
   print('remove from clients:',self)
   clients.remove(self)

class HTTPServer(asyncore.dispatcher):

   def __init__(self, port):
   asyncore.dispatcher.__init__(self)
   self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
   self.bind(("", port))
   self.listen(5)

   def handle_accept(self):
   conn, addr = self.accept()
   print('a new customer!')
   HTTPChannel(self, conn, addr)


#
# try it out
if __name__ == "__main__":
   s = HTTPServer(PORT)
   print ("serving at port", PORT, "...")

   #push data lock
   pushLock = threading.Lock()


   clients=[]

   cid = 0

   manager = Manager()

   taskList = manager.Queue()

   msgList = manager.Queue()


   h = Process(target=handler,args=(taskList,msgList))
   h.start()


   _thread.start_new_thread(sender,())
   print('entering loop')
   asyncore.loop()
--
http://mail.python.org/mailman/listinfo/python-list


how to use logging module to log an object like print()

2008-10-29 Thread davy zhang
mport logging
import pickle


# create logger
logger = logging.getLogger("simple_example")
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
- %(message)s ")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)

d = {'key':'msg','key2':'msg2'}

# "application" code
logger.debug("debug message",d)#can not do this
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to use logging module to log an object like print()

2008-10-29 Thread davy zhang
thanks so much , I ganna check the formatter str for more info:)

On Wed, Oct 29, 2008 at 5:10 PM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> davy zhang schrieb:
>>
>> mport logging
>> import pickle
>>
>>
>> # create logger
>> logger = logging.getLogger("simple_example")
>> logger.setLevel(logging.DEBUG)
>> # create console handler and set level to debug
>> ch = logging.StreamHandler()
>> ch.setLevel(logging.DEBUG)
>> # create formatter
>> formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s
>> - %(message)s ")
>> # add formatter to ch
>> ch.setFormatter(formatter)
>> # add ch to logger
>> logger.addHandler(ch)
>>
>> d = {'key':'msg','key2':'msg2'}
>>
>> # "application" code
>> logger.debug("debug message",d)#can not do this
>
> logger.debug("yes you can: %r", d)
>
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


is there a way to access postgresql in python3.0rc1

2008-10-29 Thread davy zhang
I'm currently on a  project, it could last for at least 1 or 2 years.
so I choose python3 as server side programing language.
All I found on are python2.x ready libraries, Is there any library is
python3.0 ready? or just under alpha ,beta or something, I don't much
features, just basic functions are OK

Thanks for any hint~
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a way to access postgresql in python3.0rc1

2008-10-29 Thread davy zhang
thanks, I'll wait a month and see, in the mean time I can use 2.x for
my prototyping, hope python3.0 final can drop a nuke on the ground :D

On Thu, Oct 30, 2008 at 12:31 PM, Steve Holden <[EMAIL PROTECTED]> wrote:
> Terry Reedy wrote:
>> davy zhang wrote:
>>> I'm currently on a  project, it could last for at least 1 or 2 years.
>>> so I choose python3 as server side programing language.
>>> All I found on are python2.x ready libraries, Is there any library is
>>> python3.0 ready? or just under alpha ,beta or something, I don't much
>>> features, just basic functions are OK
>>
>> Python3.0 final should be released in about a month.  Extension
>> libraries will start appearing after that.  You will have to ask the
>> maintainers of a particular library what their plans are for Python 3.
>> Some will port very easily and could be available soon.  Others will
>> take more work and may not appear so soon.
>>
> Please note, however, that Python 3.x is not likely to be as
> well-supported by extension modules as Python 2.x for some considerable
> time. The OP may therefore wish to reconsider his choice of Python 3.0.
>
> regards
>  Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Is there a way to step debug the multiprocessing python program?

2008-11-07 Thread davy zhang
I mean every process attach like thread in wingide

like thread or tasklet in wingide

:)

maybe I asked t much:D
--
http://mail.python.org/mailman/listinfo/python-list


concurrency program design stackless python tasklet or python thread?

2008-11-10 Thread davy zhang
first here is my basic idea is every actor holds their own msg queue,
the process function will handle the message as soon as the dispatcher
object put the message in.

This idea naturally leads me to place every actor in a separate thread
waiting for msg

but the rumor has it, stackless python with tasklet and channel can do
much more better in concurrency program, so I dive my head into it.

but I found the tasklet is really a lined-up sequence , that means if
a tasklet blocked or do some time consuming calculation, the other
tasklets can not get the cpu slice

so we must design very carefully to avoid the big job for single task

I am just confused why the stackless python is said to be good at
concurrency program model or just I get a wrong idea to practice?
--
http://mail.python.org/mailman/listinfo/python-list


Re: concurrency program design stackless python tasklet or python thread?

2008-11-10 Thread davy zhang
thanks very much for the hint,  circuits is a very good event-driven
frame work just like twisted

but currently my project is in a pretty much complex way

see, I'm designing a so called "Game Server", every client has their
own task execution order, see like below:

1.clientA wants to sale his armor
2.clientA wants to buy the knife
3.clientA wants to talk to npc

I think for one client this sequence should be lined-up, the task
should follow the 1,2,3step

but there's multiple clients on this server so for multiple clients
they can not wait until clientA finishing his job. if there's clientB
like below:

1.clientB wants to say something to npc
2.clientB wants to attack clientC
3.clientB wants to draw his sword

the whole process for the server should be like this sequence:


1.clientA wants to sale his armor
2.clientB wants to say something to npc
3.clientB wants to attack clientC
4.clientA wants to buy the knife
5.clientA wants to talk to npc
6.clientB wants to draw his sword

for clientA and clientB separately their tasks are lined-up, for whole
system they are concurrent

and plus I don't want to block the whole task system when a single
client dealing with big chunk task.

I don't know if I get picture right:)

any idea about my design? thanks a lot
--
http://mail.python.org/mailman/listinfo/python-list


Re: concurrency program design stackless python tasklet or python thread?

2008-11-12 Thread davy zhang
thank you very much for the advices!

I asked myself many times, why not just use thread:D

After some research I found thread has some fatal defects

1. thread number is limited by os, that means the system don't want
you start many threads at the same time
2. thread pool is another approach for concurrent program, but the
context switching could be very costy

so here comes stackless way?


On Wed, Nov 12, 2008 at 12:10 AM, Aleksandar Radulovic <[EMAIL PROTECTED]> 
wrote:
> Hi there,
>
> On Tue, Nov 11, 2008 at 5:57 AM, davy zhang <[EMAIL PROTECTED]> wrote:
>> first here is my basic idea is every actor holds their own msg queue,
>> the process function will handle the message as soon as the dispatcher
>> object put the message in.
>
> Using stackless, every tasklet can have a channel which it uses to communicate
> with other tasklets. The tasklet is blocked until there's something on
> the channel
> to receive.
>
>> This idea naturally leads me to place every actor in a separate thread
>> waiting for msg
>
> You can have actors with many separate tasklets waiting for messages, still
> being relatively lightweight, meaning you can run thousands of tasklets 
> without
> serious lack of performance.
>
>> but I found the tasklet is really a lined-up sequence , that means if
>> a tasklet blocked or do some time consuming calculation, the other
>> tasklets can not get the cpu slice
>
> This is cooperative scheduling, which you can choose not to use with Stackless
> (instead, use preemptive scheduling). If you determine that one particular
> task is taking too much cpu, you can declaratively call stackless.schedule()
> and put that task back to the scheduler queue and allow other tasks to
> have a go.
>
>> so we must design very carefully to avoid the big job for single task
>
> That's right - with cooperative scheduling careful design is the key.
>
>> I am just confused why the stackless python is said to be good at
>> concurrency program model or just I get a wrong idea to practice?
>
> Stackless is an extremely lightweight way into concurrent programming.
> I have personally used it in few projects and i quite like how lightweight
> it is and how easy it is to write concurrent programs.
>
> On the plus side, Stackless developers have plenty of examples and
> common idioms of how Stackless should be used, which I highly recommend
> you to check out. You might find a solution to your problem right there
> amongst the examples.
>
>
> Check it all out on http://www.stackless.com
>
> --
> a lex 13 x
> http://www.a13x.info
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


win32com.client (Howto edit Contacts in Outlook)

2008-07-04 Thread Bill Davy
I am trying to edit Contacts in Outlook.  This is so I can transfer numbers 
from my address book which is an Excel spreadsheet to my mobile phone.  I 
came across the following snippet of code which enabled me to the contacts 
at least list.  I had to root around to discover CdoDefaultFolderContacts 
(though it was guessable; how could I enumerate win32com.client.constants?).



I now want to work through the Contacts in Outlook patching in data from my 
spreadsheet, and also making new contacts where there is an entry in my 
spreadsheet which has not gone into Contacts already.



Where can I find the API?  I downloaded OutlookSpy but it is not clear to me 
that it can display the structure of the data, nor does it list methods for 
objects (a Contact, a Folder of Contacts) that I had hoped.



TIA,

Bill



class Folder (object):
  def __init__ (self, folder):
self._folder = folder
  def __getattr__ (self, attribute):
return getattr (self._folder, attribute)
  def __iter__ (self):
#
# NB You *must* collect a reference to the
# Messages collection here; otherwise GetFirst/Next
# resets every time.
#
messages = self._folder.Messages
message = messages.GetFirst ()
while message:
  yield message
  message = messages.GetNext ()

if __name__ == '__main__':
  import win32com.client
  session = win32com.client.gencache.EnsureDispatch ("MAPI.Session")
  constants = win32com.client.constants
  session.Logon ("Outlook")

  #
  # CdoDefaultFolderInbox
  # CdoDefaultFolderSentItems
  # CdoDefaultFolderContacts
  #
  contact_items = Folder (session.GetDefaultFolder 
(constants.CdoDefaultFolderContacts))
  for message in contact_items:
print message
sys.exit(1)
print message.Subject 


--
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-04 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> I am trying to edit Contacts in Outlook.  This is so I can transfer 
>> numbers from my address book which is an Excel spreadsheet to my mobile 
>> phone.  I came across the following snippet of code
>
> --- hey! that looks familiar :)
>
>> which enabled me to the contacts at least list.  I had to root around to 
>> discover CdoDefaultFolderContacts (though it was guessable; how could I 
>> enumerate win32com.client.constants?).
>
> Well that bit's easy: win32com.client.constants is a small class with
> a __dicts__ attribute (note the "s") which is a list of dictionaries, one
> per generated library. So you can do something like this:
>
> 
> import win32com.client
>
> outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
> outlook_constants = win32com.client.constants.__dicts__[0]
>
> for k, v in outlook_constants.items ():
>  print k, "=>", v
>
> 
>
>> I now want to work through the Contacts in Outlook patching in data from 
>> my spreadsheet, and also making new contacts where there is an entry in 
>> my spreadsheet which has not gone into Contacts already.
>
> OK.
>
>> Where can I find the API?
>
> I recommend:
>
>  http://msdn.microsoft.com/en-us/library/ms526861.aspx
>
> and
>
>  http://www.outlookcode.com/article.aspx?id=20
>
> and
>
>  http://www.cdolive.com/cdo10.htm
>
> TJG


Brilliant.  But I was a bit disappointed by one experiment.  In MSDN I found 
"Exploring the Outlook Object Model".  That suggested:
Outlook | Tools | Macros | VB Editor | View | Object Browser

There I found ContactItems and reckoned I was onto a winner, but found that 
a "message" from the ContactFolder might have Subject but it did not have a 
FullName.  Also, if Python crashed, it left Outlook complaing that someone 
was accessing it but had disappeaared so Outlook has to be restarted each 
time.

But you have suggested some more things to look at so thanks.  I have had a 
quick look but have not so far even found "Subject" as a member/property of 
a message/contact.  I shall keep looking.

Rgds,
   Bill 


--
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-04 Thread Bill Davy
"Bill Davy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Tim Golden" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> Bill Davy wrote:
>>> I am trying to edit Contacts in Outlook.  This is so I can transfer 
>>> numbers from my address book which is an Excel spreadsheet to my mobile 
>>> phone.  I came across the following snippet of code
>>
>> --- hey! that looks familiar :)
>>
>>> which enabled me to the contacts at least list.  I had to root around to 
>>> discover CdoDefaultFolderContacts (though it was guessable; how could I 
>>> enumerate win32com.client.constants?).
>>
>> Well that bit's easy: win32com.client.constants is a small class with
>> a __dicts__ attribute (note the "s") which is a list of dictionaries, one
>> per generated library. So you can do something like this:
>>
>> 
>> import win32com.client
>>
>> outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
>> outlook_constants = win32com.client.constants.__dicts__[0]
>>
>> for k, v in outlook_constants.items ():
>>  print k, "=>", v
>>
>> 
>>
>>> I now want to work through the Contacts in Outlook patching in data from 
>>> my spreadsheet, and also making new contacts where there is an entry in 
>>> my spreadsheet which has not gone into Contacts already.
>>
>> OK.
>>
>>> Where can I find the API?
>>
>> I recommend:
>>
>>  http://msdn.microsoft.com/en-us/library/ms526861.aspx
>>
>> and
>>
>>  http://www.outlookcode.com/article.aspx?id=20
>>
>> and
>>
>>  http://www.cdolive.com/cdo10.htm
>>
>> TJG
>
>
> Brilliant.  But I was a bit disappointed by one experiment.  In MSDN I 
> found "Exploring the Outlook Object Model".  That suggested:
> Outlook | Tools | Macros | VB Editor | View | Object Browser
>
> There I found ContactItems and reckoned I was onto a winner, but found 
> that a "message" from the ContactFolder might have Subject but it did not 
> have a FullName.  Also, if Python crashed, it left Outlook complaing that 
> someone was accessing it but had disappeaared so Outlook has to be 
> restarted each time.
>
> But you have suggested some more things to look at so thanks.  I have had 
> a quick look but have not so far even found "Subject" as a member/property 
> of a message/contact.  I shall keep looking.
>
> Rgds,
>   Bill
>


I kept looking and thought I was saved when I found Receipe 10.16 in the 
Python Cookbook but 

I changed the following:

self.oOutlookApp = Dispatch("Outlook.Application")
#self.oOutlookApp = 
gencache.EnsureDispatch("Outlook.Application")

Because gencache failed and I hade run makepy last week (I only get one day 
a week to look at this).

Then the following failed because (as I found) olFolderContacts is not in 
any of constants' dictionaries.

ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts)

So, sadly, I shall have to put this aside for another week and get on with 
some work.  Any thoughts would be gratefully accepted.

TIA,
   Bill 


--
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-10 Thread Bill Davy
"Tim Roberts" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Bill Davy" <[EMAIL PROTECTED]> wrote:
>>
>>I am trying to edit Contacts in Outlook.  This is so I can transfer 
>>numbers
>>from my address book which is an Excel spreadsheet to my mobile phone.
>
> Are you actually running Outlook?  Your news posting was made from Outlook
> Express, and Outlook Express cannot be controlled by COM (although MAPI
> works).
> -- 
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.


I'm not sure OL2003 can read news.  I think perhaps some later OL can (added 
tot he View menu, perhaps?).  So I use OL Express to read news.  The OL with 
which I wish to communicate is:

Application name Outlook
Version 11.0
Build 8217
Product ID 70141-700-0350904-56905
Language English (United States)
Application Path C:\Program Files\Microsoft Office\OFFICE11\
System Language English (United Kingdom)
Mail Support Not Available
Current folder Inbox
Current item Not Available

Not sure why its says "Mail Support Not Available" as all I use it for is 
email (oh, and the calendar).

Hey and ho
Bill 


--
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-11 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> I'm not sure OL2003 can read news.  I think perhaps some later OL can 
>> (added tot he View menu, perhaps?).  So I use OL Express to read news. 
>> The OL with which I wish to communicate is:
>>
>> Application name Outlook
>> Version 11.0
>> Build 8217
>> Product ID 70141-700-0350904-56905
>> Language English (United States)
>> Application Path C:\Program Files\Microsoft Office\OFFICE11\
>> System Language English (United Kingdom)
>> Mail Support Not Available
>> Current folder Inbox
>> Current item Not Available
>
> Where did you get to with this, Bill? I wasn't sure if no news
> was good news or whether you'd gone a different way, or
> were still trying things...
>
> TJG


Hi Tim,
Well, at 5pm last Friday I posted:
"

I kept looking and thought I was saved when I found Receipe 10.16 in the
Python Cookbook but 

I changed the following:

self.oOutlookApp = Dispatch("Outlook.Application")
#self.oOutlookApp =
gencache.EnsureDispatch("Outlook.Application")

Because gencache failed and I hade run makepy last week (I only get one day
a week to look at this).

Then the following failed because (as I found) olFolderContacts is not in
any of constants' dictionaries.

ofContacts = onMAPI.GetDefaultFolder(constants.olFolderContacts)

So, sadly, I shall have to put this aside for another week and get on with
some work.  Any thoughts would be gratefully accepted.

TIA,
   Bill
"

and since then have been busy with work, and my other job, and the garden. 
Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E etc 
etc but that's another story).  So any help today will be much appreciated.
Rgds,
   Bill 


--
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-11 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> and since then have been busy with work, and my other job, and the 
>> garden.
>
> Aha! So you're English, are you? Looks like you're in the West Country.
> Weather map suggests you're not short of rain over there :)
>
>> Now I am back looking at this (and using WInUSB to talk to a Maxim 3421E 
>> etc etc but that's another story).  So any help today will be much 
>> appreciated.
>> Rgds,
>
> Can't remember what the particular obstacles were you
> were facing, but this runs OK on my setup -
> Python 2.5.2 / pywin32 211 / Outlook 2003:
>
> 
> import os, sys
> import win32com.client
> constants = win32com.client.constants
>
> def items (contacts):
>  items = contacts.Items
>  item = items.GetFirst ()
>  while item:
>yield item
>item = items.GetNext ()
>
> #
> # Add whatever fields you like from:
> # http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx
> #
> FIELDS = ['FullName', 'CompanyName', 'Email1Address']
>
> outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
> ns = outlook.GetNamespace ("MAPI")
> for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
>  if contact.Class == constants.olContact:
>print contact
>for field in FIELDS:
>  print "  ", field, "=>", getattr (contact, field, "")
>
> 
>
> Hope that helps.
> TJG


jUST IN CASE,. i CUT'NPASTED THE PROGRAM:

import os, sys
import win32com.client
constants = win32com.client.constants

def items (contacts):
  items = contacts.Items
  item = items.GetFirst ()
  while item:
yield item
item = items.GetNext ()

#
# Add whatever fields you like from:
# http://msdn.microsoft.com/en-us/library/aa210907(office.11).aspx
#
FIELDS = ['FullName', 'CompanyName', 'Email1Address']

outlook = win32com.client.gencache.EnsureDispatch ("Outlook.Application")
ns = outlook.GetNamespace ("MAPI")
for contact in items (ns.GetDefaultFolder (constants.olFolderContacts)):
  if contact.Class == constants.olContact:
print contact
for field in FIELDS:
  print "  ", field, "=>", getattr (contact, field, "")

---
And then I ran it:

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] 
on win32
Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.2.2
>>>  RESTART 
>>> 
>>>

Traceback (most recent call last):
  File "H:/Personal/OutlookIF1/t2.py", line 18, in 
outlook = win32com.client.gencache.EnsureDispatch 
("Outlook.Application")
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
bForDemand=bForDemand)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>>>

-

Outlook is running fine.

This is how the fucntion where the failure occurs begins:

def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, 
bFlushNow = not is_readonly):
 """Add a newly generated file to the cache dictionary.
 """
 fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
 mod = _GetModule(fname)
 # if mod._in_gencache_ is already true, then we are reloading this
 # module - this doesn't mean anything special though!
 mod._in_gencache_ = 1
 dict = mod.CLSIDToClassMap
 info = str(typelibclsid), lcid, major, minor
 for clsid, cls in dict.items():
  clsidToTypelib[clsid] = info

---

Yes, we have suffiicient rain but the gaden needed it.  I am about to become 
the proud tenant of half an allotment.  Still, this time last year we had 
floods.

TIA,
   Bill 


--
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client (Howto edit Contacts in Outlook)

2008-07-12 Thread Bill Davy
"Tim Golden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bill Davy wrote:
>> Traceback (most recent call last):
>>   File "H:/Personal/OutlookIF1/t2.py", line 18, in 
>> outlook = win32com.client.gencache.EnsureDispatch 
>> ("Outlook.Application")
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 536, in EnsureDispatch
>> mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
>> bForDemand=bForDemand)
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 393, in EnsureModule
>> module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 262, in GetModuleForTypelib
>> AddModuleToCache(typelibCLSID, lcid, major, minor)
>>   File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
>> 554, in AddModuleToCache
>> dict = mod.CLSIDToClassMap
>> AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>
>
> Just in case, could you delete the contents of your gen_py
> directory (probably in %TEMP%\gen_py)
>
> TJG



OK, Put the following ahead with the following results.

TempDir = os.getenv("TEMP");
WorkDir = TempDir + '\\gen_py'
print WorkDir
try:
  os.rmdir(WorkDir);
except  WindowsError, detail:
  print "Ignoring Windows error: ", detail

...

Result:


C:\DOCUME~1\Bill\LOCALS~1\Temp\gen_py
Ignoring Windows error:  [Error 2] The system cannot find the file 
specified: 'C:\\DOCUME~1\\Bill\\LOCALS~1\\Temp\\gen_py'

Traceback (most recent call last):
  File "H:\Personal\OutlookIF1\t2.py", line 26, in 
outlook = win32com.client.gencache.EnsureDispatch 
("Outlook.Application")
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
536, in EnsureDispatch
mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], 
bForDemand=bForDemand)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
393, in EnsureModule
module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
262, in GetModuleForTypelib
AddModuleToCache(typelibCLSID, lcid, major, minor)
  File "C:\Python25\Lib\site-packages\win32com\client\gencache.py", line 
554, in AddModuleToCache
dict = mod.CLSIDToClassMap
AttributeError: 'module' object has no attribute 'CLSIDToClassMap'
>>>

So, although that directory did exist, it does not now (even after the 
program has run).

Any other ideas?

But many thnaks,
Bill 


--
http://mail.python.org/mailman/listinfo/python-list


..\..\Python-2.5.2\Include\pyport.h(117) : fatal error C1189: #error : "Python needs a typedef for Py_ssize_t in pyport.h."

2008-07-12 Thread Bill Davy
When I try and compile using VS2003 for Release.  Compiles fine for Debug. 
In a hurry (should be gardening).  Any solution?

TIA
Bill 


--
http://mail.python.org/mailman/listinfo/python-list


SWIG/C++

2008-04-10 Thread Bill Davy
Is there a better place to post such questions?

Anyway, in the hope it is something simple, I would appreciate some help.

I am adding some C++ code to Python.  From Python I want to be able to read 
data from a target device, over USB.  My software does all the hard work and 
I have a class:

class ViperUsbC
{
public:
// snip snip
ERROR_T ReadSlaveMemory(u8 Slave, u16 Offset, u8* pData, u16 
Length);
// Snip,snip
};

I use swigwin-1.3.34 to wrap it into a module called SHIP.

In Python, I have:

import SHIP
ViperUsb = SHIP.ViperUsbC()
Slave =7
Offset = 0
Length = 64
Buffer = 'a' * Length
print "type(Buffer)=%s" % type(Buffer)
print "len(Buffer)=%s" % len(Buffer)
Result = ViperUsb.ReadSlaveMemory(Slave, Offset, Buffer, Length);

That fails with:

type(Buffer)=
len(Buffer)=64

Traceback (most recent call last):
  File "H:\Husky\HostPC\V1\SHIP\test1.py", line 1970, in -toplevel-
ViperTests()
  File "H:\Husky\HostPC\V1\SHIP\test1.py", line 1884, in ViperTests
Result = ViperUsb.ReadSlaveMemory(Slave, Offset, Buffer, Length);
  File "H:\Husky\HostPC\V1\SHIP\Release\SHIP.py", line 1757, in 
ReadSlaveMemory
def ReadSlaveMemory(*args): return 
_SHIP.ViperUsbC_ReadSlaveMemory(*args)
TypeError: in method 'ViperUsbC_ReadSlaveMemory', argument 4 of type 'u8 *'


How do I provide a buffer into which to read the data?  It would not be 
intolerable to provide another layer using %extend, but I feel sure this 
should be automagic.

Thanks in advance
Bill

PS This is a very small part of a much larger project so I cannot supply 
complete source code. 


-- 
http://mail.python.org/mailman/listinfo/python-list


"Python failed to load the default activation context" - should I worry?

2010-06-08 Thread Bill Davy
Loading Python 2.6.5 (built using VC6) in a VC6 application.  This appears 
in my debug log.  Am I worried?  Should I be?
And I am stuck with VC6 (customers, don't ya know). 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python source code -> win/dos executable (on linux)

2010-07-01 Thread Bill Davy
"Stephen Hansen"  wrote in message 
news:mailman.2344.1277821469.32709.python-l...@python.org...
> On 6/29/10 12:27 AM, Lawrence D'Oliveiro wrote:
>> In message<4c286d71$0$18654$4fafb...@reader3.news.tin.it>, superpollo
>> wrote:
>>
>>> Lawrence D'Oliveiro ha scritto:

 Is it really such a hassle to install things on Windows?
>>>
>>> no, but it *IS* to explain it to dumb users... :-(
>>
>> Can't you create an installation package that specifies Python and all 
>> the
>> other necessary dependencies, so the Windows package-management system 
>> will
>> automatically pull the right versions in when the user does the
>> installation?
>
> At first, on reading this, I assumed it was sarcastic (and sort of decided 
> not to reply, because anti-windows is too easy); but on reading again I'm 
> not so sure, you're writing it all out so .. dry. Then again, 'hearing' 
> tone in text is hard.
>
> If this isn't sarcastic: windows has no package management system. You 
> include every dependency manually (in varying forms) or things don't run.
>
> Windows has a way to track what you install, and the ability to uninstall 
> about three fourths of it later. That's it.
>
> -- 
>
>... Stephen Hansen
>... Also: Ixokai
>... Mail: me+list/python (AT) ixokai (DOT) io
>... Blog: http://meh.ixokai.io/
>


Not that I am a supporter of Windows nor an expert at MSI BUT later versions 
of Visual Studio do have a mechanism for building a package.  I know it's 
not in VC6, but is in VS.2008.
HTH,
   Bill 


-- 
http://mail.python.org/mailman/listinfo/python-list


ImportError: DLL load failed: The specified module could not be found, SWIG, life, etc

2010-07-05 Thread Bill Davy
I am struggling :-(



I have used SWIG to build a module called SHIP.  So I have a directory 
containing SHIP.py and _SHIP.pyd, as follows:



H:\Viper\HostPC\V1\SHIP\Release>dir

 Volume in drive H has no label.

 Volume Serial Number is B83B-76F2



 Directory of H:\Viper\HostPC\V1\SHIP\Release



05/07/2010  14:43  .

05/07/2010  14:43  ..

03/07/2010  16:2841,079 SHIP.py

03/07/2010  14:36   495,616 _SHIP.pyd

   2 File(s)536,695 bytes

   2 Dir(s)  58,270,535,680 bytes free







I have a test Python program which imports sys and os and then attempts to 
import SHIP; it begins as follows:





## D for John's notebook

## E for Rod's notebook

## H for Bill's notebook

DRIVE = 'H:'



import sys

import os

if ( not os.path.exists(DRIVE) ):

print "Drive \'%s\' does not exist on this machine; edit top of file" % 
(DRIVE)

sys.exit(0)



# Prepend our path

sys.path[:0] = [DRIVE + r'\Viper\HostPC\V1\SHIP\Release']



import SHIP



SHIP.Initialise();





I then create a Command Prompt window and enter:





H:\Viper\HostPC\V1\SHIP>C:\Python26\python -vv Test1.py >tmp.txt 2>&1



In tmp.txt, I see the following:





Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] 
on win32

Type "help", "copyright", "credits" or "license" for more information.

# trying H:\Viper\HostPC\V1\SHIP\Release\SHIP.pyd

# trying H:\Viper\HostPC\V1\SHIP\Release\SHIP.py

# H:\Viper\HostPC\V1\SHIP\Release\SHIP.pyc matches 
H:\Viper\HostPC\V1\SHIP\Release\SHIP.py

import SHIP # precompiled from H:\Viper\HostPC\V1\SHIP\Release\SHIP.pyc

# trying H:\Viper\HostPC\V1\SHIP\Release\_SHIP.pyd

#   clear[2] __name__

#   clear[2] __file__

Traceback (most recent call last):

  File "Test1.py", line 15, in 

import SHIP

  File "H:\Viper\HostPC\V1\SHIP\Release\SHIP.py", line 7, in 

import _SHIP

ImportError: DLL load failed: The specified module could not be found.





It would seem the "import SHIP" is finding SHIP.py without any trouble.

SHIP.py begins by "import _SHIP".

Python appears to find H:\Viper\HostPC\V1\SHIP\Release\_SHIP.pyd but for 
some reason, which I cannot fathom, says "DLL load failed".



Can anyone offer me any suggestion where I am going wrong or how to tackle 
this problem?



Could it be that the Python 2.6 I am running did not use the same compiler 
(VC6) with which I buiult _SHIP.pyd and if so, is there a way round this 
without moving on from VC6?



TIA,

   Bill


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ImportError: DLL load failed: The specified module could notbe found, SWIG, life, etc

2010-07-05 Thread Bill Davy
"Thomas Jollans"  wrote in message 
news:mailman.265.1278342154.1673.python-l...@python.org...
> On 07/05/2010 04:35 PM, Bill Davy wrote:
>> I am struggling :-(
>
> smile!
>
>>
>> I have used SWIG to build a module called SHIP.  So I have a directory
>> containing SHIP.py and _SHIP.pyd, as follows:
>>
>> [ ...]
>>
>> Python appears to find H:\Viper\HostPC\V1\SHIP\Release\_SHIP.pyd but for
>> some reason, which I cannot fathom, says "DLL load failed".
>>
>
> Maybe it doesn't mean _SHIP.pyd, but another DLL: maybe _SHIP.pyd
> depends on some other DLL? Since you used SWIG, I'm guessing that you're
> wrapping some other library. Maybe that's what it can't find.
>

Well, there's no mention of another librarary, and "import _SHIP" is the 
first (non-comment) statement in SHIP.py
But when I run Dependency Walker against _SHIP.pyd it does say there's a 
missing DLL (WINUSB.DLL) so I suspect I've got to sort that out.

>>
>>
>> Can anyone offer me any suggestion where I am going wrong or how to 
>> tackle
>> this problem?
>>
>>
>>
>> Could it be that the Python 2.6 I am running did not use the same 
>> compiler
>> (VC6) with which I buiult _SHIP.pyd and if so, is there a way round this
>> without moving on from VC6?
>>
>
> Shouldn't be a problem, as long as the calling convention hasn't change,
> which it hasn't. If you're on a 64-bit system there might be a problem
> there with Python and some DLLs being built for different architectures?

Yep, all for the same architetcure.  I suspect it's a dependency problem. 
Oh well.

>
> Cheers,
> Thomas



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: missing 'xor' Boolean operator

2009-07-15 Thread Bill Davy
"MRAB"  wrote in message 
news:mailman.3158.1247667680.8015.python-l...@python.org...
> Steven D'Aprano wrote:
>> On Tue, 14 Jul 2009 11:25:08 -0700, Dr. Phillip M. Feldman wrote:
>>
>>> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice
>>> to have an 'xor' operator as well.
>>
>> I've often wished there was too, for the sake of completeness and 
>> aesthetics, I'd love to be able to write:
>>
>> a xor b
>>
>> instead of defining a function xor(a, b).
>>
>> Unfortunately, outside of boolean algebra and simulating electrical 
>> circuits, I can't think of any use-cases for an xor operator. Do you have 
>> any?
>>
> The problem is that 'and' and 'or' are not limited to Boolean values:
>
> 'and' returns the first false value or the last true value.
>
> 'or' returns the first true value or the last false value.
>
> What values should 'xor' return? IMHO, if only one of the values is true
> then it should return that value, otherwise it should return False.
>
> 1 xor 0 => 1
> 0 xor 2 => 2
> 1 xor 2 => False
> 0 xor 0 => False
>
> This is because it's a Boolean operator, so it should fall back to
> Boolean values when necessary, like 'not':
>
> not 0 => True
> not 1 => False
>
> Also:
>
> x and y and z => (x and y) and z
> x or y or z => (x or y) or z
>
> therefore:
>
> x xor y xor z => (x xor y) xor z


Gosh, let's all discuss commutation and distribution.

And surely in quantum merchanics there is something about non-commuting 
operatiomns letting in Planck's constant. 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regex: multiple matching for one string

2009-07-23 Thread Bill Davy
"Mark Lawrence"  wrote in message 
news:mailman.3588.1248355389.8015.python-l...@python.org...
> scriptlear...@gmail.com wrote:
>> For example, I have a string "#a=valuea;b=valueb;c=valuec;", and I
>> will like to take out the values (valuea, valueb, and valuec).  How do
>> I do that in Python?  The group method will only return the matched
>> part.  Thanks.
>>
>> p = re.compile('#a=*;b=*;c=*;')
>> m = p.match(line)
>> if m:
>>  print m.group(),
>
> IMHO a regex for this is overkill, a combination of string methods such as 
> split and find should suffice.
>
> Regards.
>


For the OP, it can be done with regex by grouping:

p = re.compile(r'#a=(*);b=(*);c=(*);')
m = p.match(line)
   if m:
 print m.group(1),

m.group(1) has valuea in it, etc.

But this may not be the best way, but it is reasonably terse. 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read C++ enum in python

2009-08-19 Thread Bill Davy
"Mark Tolonen"  wrote in message 
news:mailman.89.1250666942.2854.python-l...@python.org...
>
> "MRAB"  wrote in message 
> news:4a8b3e2d.7040...@mrabarnett.plus.com...
>> Ludo wrote:
>>> Hello,
>>>
>>> I work in a very large project where we have C++ packages and pieces of 
>>> python code.
>>>
>>> I've been googleing for days but what I find seems really too 
>>> complicated for what I want to do.
>>>
>>> My business is, in python, to read enum definitions provided by the 
>>> header file of an c++ package.
>>> Of course I could open the .h file, read the enum and transcode it by 
>>> hand into a .py file but the package is regularly updated and thus is 
>>> the enum.
>>>
>>> My question is then simple : do we have :
>>> - either a simple way in python to read the .h file, retrieve the 
>>> c++ enum and provide an access to it in my python script
>>> - either a simple tool (in a long-term it would be automatically run 
>>> when the c++ package is compiled) generating from the .h file a .py file 
>>> containing the python definition of the enums ?
>>>
>>> Thank you for any suggestion.
>>
>> Speaking personally, I'd parse the .h file using a regular expression
>> (re module) and generate a .py file. Compilers typically have a way of
>> letting you run external scripts (eg batch files in Windows or, in this
>> case, a Python script) when an application is compiled.
>
> This is what 3rd party library pyparsing is great for:
>
> begin code--
> from pyparsing import *
>
> # sample string with enums and other stuff
> sample = '''
>stuff before
>
>enum hello {
>Zero,
>One,
>Two,
>Three,
>Five=5,
>Six,
>Ten=10
>}
>
>in the middle
>
>enum blah
>{
>alpha,
>beta,
>gamma = 10 ,
>zeta = 50
>}
>
>at the end
>'''
>
> # syntax we don't want to see in the final parse tree
> _lcurl = Suppress('{')
> _rcurl = Suppress('}')
> _equal = Suppress('=')
> _comma = Suppress(',')
> _enum = Suppress('enum')
>
> identifier = Word(alphas,alphanums+'_')
> integer = Word(nums)
>
> enumValue = Group(identifier('name') + Optional(_equal + 
> integer('value')))
> enumList = Group(enumValue + ZeroOrMore(_comma + enumValue))
> enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl
>
> # find instances of enums ignoring other syntax
> for item,start,stop in enum.scanString(sample):
>id = 0
>for entry in item.list:
>if entry.value != '':
>id = int(entry.value)
>print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id)
>id += 1
> --end code
>
> Output:
> HELLO_ZERO = 0
> HELLO_ONE = 1
> HELLO_TWO = 2
> HELLO_THREE = 3
> HELLO_FIVE = 5
> HELLO_SIX = 6
> HELLO_TEN = 10
> BLAH_ALPHA = 0
> BLAH_BETA = 1
> BLAH_GAMMA = 10
> BLAH_ZETA = 50
>
> -Mark
>
>


Python and pythoneers are amazing! 


-- 
http://mail.python.org/mailman/listinfo/python-list