Python-Excel: How to paste selected cells (range) to different location on the same sheet in Excel

2005-08-03 Thread zxo102
Hi there,
I need your help for python <--> excel. I want to paste selected
cells (range) to different location on the same sheet in Excel through
python. I have tried it for a while but could not figure it out. Here
is my sample code:

import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Visible=1
wb = xl.Workbooks.Add( )
sh=wb.Worksheets(1)
sh.Cells(1,1).Value = "Hello World!"
sh.Cells(3,3).Value = "Hello World!"
sh.Range(sh.Cells(1,1),sh.Cells(3,3)).Select()
sh.Range(sh.Cells(1,1),sh.Cells(3,3)).Copy()
# sh.Range(sh.Cells(4,1),sh.Cells(6,3)).Paste()

The last line of the code does not work.

Thanks you very much.

Ouyang

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


Re: Python-Excel: How to paste selected cells (range) to different location on the same sheet in Excel

2005-08-03 Thread zxo102
I found the solution for this. It needs to select a new location and
paste from "sh". Thank you for your reading this.

import win32com.client
xl=win32com.client.Dispatch("E­xcel.Application")
xl.Visible=1
wb = xl.Workbooks.Add( )
sh=wb.Worksheets(1)
sh.Cells(1,1).Value = "Hello World!"
sh.Cells(3,3).Value = "Hello World!"
sh.Range(sh.Cells(1,1),sh.Cell­s(3,3)).Select()
sh.Range(sh.Cells(1,1),sh.Cell­s(3,3)).Copy()
sh.Cells(4,1).Select()
sh.Paste() 


Ouyang

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


list to tuple

2005-08-11 Thread zxo102
Hi,
   I got several dynamic lists a1, b1, c1,  from a python
application such as
   a1 = [1,5,3,2,5,...], the len(a1) varies. Same to b1, c1, 

   With python, I would like to reorganize them into a tuple like

   t1 = ((a1[0],b1[0],c1[0],...),(a1[1],b1[1],c1[1],...),...)

  Anybody knows how to do that. Thanks for your help.

Ouyang

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


Re: list to tuple

2005-08-11 Thread zxo102
Thanks for your help.

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


python-Excel: Chinese Characters

2005-08-14 Thread zxo102
Hi there,
I am trying to put data including Chinese Characters into Excel
through python. But I got some problems. Here is my sample code:

##
#
import win32com.client
xlapp  = win32com.client.DispatchEx("Excel.Application")
xlbook = xlapp.Workbooks.Open("test.xls")
sht= xlbook.Worksheets("Sheet1")

# data is provided in case 1 and case 2 below
...
sht.Range(sht.Cells(1, 1), sht.Cells(2,4)).Value = data
#
##

Using the above code, I tested two cases for "data". The "data" from
both two cases are same: tuple basically. But in case 1, only  and
 are inserted into Excel. All other cells are blank. in case2, all
data including Chinese Characters are inserted into Excel and
everything is fine. My real data is like case 1.



#case 1 --
rp = {'r1':['\xd6\xd7\xc1\xf6','\xd6\xd7\xc1\xf6'],
  'r2':['\xd6\xd7\xc1\xf6','\xd6\xd7\xc1\xf6'],
  'r3':[,],
  'r4':['\xd6\xd7\xc1\xf6','\xd6\xd7\xc1\xf6']
 }

b = ()
for k in range(len(rp['r1'])):
a = rp['r1'][k],rp['r2'][k],rp['r3'][k],rp['r4'][k]
if len(b) == 0:
b = a
else:
b = b,a
data = b

#case 2 --
data   =(('\xd6\xd7\xc1\xf6', '\xd6\xd7\xc1\xf6', ,
'\xd6\xd7\xc1\xf6'),
('\xd6\xd7\xc1\xf6", '\xd6\xd7\xc1\xf6", ,
'\xd6\xd7\xc1\xf6'))

Anybody knows what is going on with it?

Thanks for your help.

Ouyang

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


Help: how to run python applications as NT service?

2005-12-12 Thread zxo102
Hi there,
I have a python application (many python scripts) and I start the
application like this

python myServer.py start

in window. It is running in dos window. Now I would like to put it in
background as NT service. I got a example code: SmallestService.py from
chapter 18 of the book "Python Programming On Win32" by Mark Hammond
etc. The code is as follows and runs well as an NT service.

Since I don't have the book, anybody knows how to "insert" my "python
myServer.py start" into the sample code as follows.

Thanks a lot for your help.

ouyang

#
import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "SmallestPythonService"
_svc_display_name_ = "The smallest possible Python Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop
process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
# And set my event.
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
# We do nothing other than wait to be stopped!
win32event.WaitForSingleObject(self.hWaitStop,
win32event.INFINITE)

if __name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)

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


Re: Help: how to run python applications as NT service?

2005-12-14 Thread zxo102

Thanks for your help, Larry.

Finally, I got it my python script run as NT service with
the attached python code which is from the site:

http://www.schooltool.org/products/schooltool-calendar/documentation/how-to/running-as-a-windows-service/schooltool-service.py/view


##
#
# Copyright (c) 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public
License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this
distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND
FITNESS
# FOR A PARTICULAR PURPOSE.
#
##

"""
Windows NT/2K service installer/controller for Zope/ZEO/ZRS instances.
"""

# With trivial modifications for use with SchoolBell and SchoolTool.

import sys, os, time
import pywintypes
import win32serviceutil
import win32service
import win32event
import win32process

# the max seconds we're allowed to spend backing off
BACKOFF_MAX = 300
# if the process runs successfully for more than BACKOFF_CLEAR_TIME
# seconds, we reset the backoff stats to their initial values
BACKOFF_CLEAR_TIME = 30
# the initial backoff interval (the amount of time we wait to restart
# a dead process)
BACKOFF_INITIAL_INTERVAL = 5

class Service(win32serviceutil.ServiceFramework):
""" A class representing a Windows NT service that can manage an
instance-home-based Zope/ZEO/ZRS processes """

# The comment below is mostly irrelevant if you're running a
standalone
# SchoolBell server, I think. -TEH

# The PythonService model requires that an actual on-disk class
declaration
# represent a single service.  Thus, the below definition of
start_cmd,
# must be overridden in a subclass in a file within the instance
home for
# each instance.  The below-defined start_cmd (and
_svc_display_name_
# and _svc_name_) are just examples.

# To use this script with SchoolTool, just replace "SchoolBell"
# with "SchoolTool" in the variables below.
# You'll also need to change 'Python24' to 'Python23' if that's
# what you've got.  -TEH

_svc_name_ = r'SchoolBell'
_svc_display_name_ = r'SchoolBell Server'

start_cmd = (
r'"C:\Python24\python.exe" '
r'"C:\Program Files\SchoolBell\schoolbell-server.py" '
)

def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
# The "service stop" request will set this event.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.redirectOutput()

def redirectOutput(self):
sys.stdout.close()
sys.stderr.close()
sys.stdout = NullOutput()
sys.stderr = NullOutput()

def SvcStop(self):
# Before we do anything, tell the SCM we are starting the stop
process.
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

# TODO:  This TerminateProcess call doesn't make much sense:
it's
# doing a hard kill _first_, never giving the process a chance
to
# shut down cleanly.  Compare to current Zope2 service code,
which
# uses Windows events to give the process a chance to shut down
# cleanly, doing a hard kill only if that doesn't succeed.

# stop the process if necessary
try:
win32process.TerminateProcess(self.hZope, 0)
except pywintypes.error:
# the process may already have been terminated
pass
# And set my event.
win32event.SetEvent(self.hWaitStop)

# SvcStop only gets triggered when the user explictly stops (or
restarts)
# the service.  To shut the service down cleanly when Windows is
shutting
# down, we also need to hook SvcShutdown.
SvcShutdown = SvcStop

def createProcess(self, cmd):
return win32process.CreateProcess(
None, cmd, None, None, 0, 0, None, None,
win32process.STARTUPINFO())

def SvcDoRun(self):
# indicate to Zope that the process is daemon managed
(restartable)
os.environ['ZMANAGED'] = '1'

# daemon behavior:  we want to to restart the process if it
# dies, but if it dies too many times, we need to give up.

# we use a simple backoff algorithm to determine whether
# we should try to restart a dead process:  for each
# time the process dies unexpectedly, we wait some number of
# seconds to restart it, as determined by the backoff interval,
# which doubles each time the process dies.  if we exceed
# BACKOFF_MAX seconds in cumulative backoff time, we give up.
# at any time if we successfully run the proce

how to show Chinese Characters in the value set of a dictionary

2006-01-01 Thread zxo102
Hi there,
  I have a dictionary with values of Chinses Characters. For
example,

>>> dict = {}
>>> dict['c1']="中国一"
>>> dict['c2']="中国二"
>>> dict.values()
['\xd6\xd0\xb9\xfa\xb6\xfe', '\xd6\xd0\xb9\xfa\xd2\xbb']

Since the result of dict.values will be inserted into web pages and
handled by javascript there, I want to show Chinese Characters
in the list directly like this,

['中国一','中国二']

Anybody knows how to do this?   Thank you very much for your help.

Ouyang

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

how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread zxo102
Hi everyone,
I am using a python socket server to collect data from a socket
client and then control a image location ( wxpython) with the data,
i.e. moving the image around in the wxpython frame.
   But  the "app.MainLoop()" in wxpython looks like conflicting with
the "while 1:" in socket server. After I commented the
"app.MainLoop()", everything is working except two things:
 1. if I click anywhere on the screen with the mouse, the image is
gong and only the empty frame( or panel) is left.
 2. if I don't  touch anything, the image is being moved around but
the previous images are left behind in the panel.
I guess that may be caused by "app.MainLoop()" commented.
   Anybody knows how to make the two things work together? I really
appreciate your help.
   My sample code is modified based on the wxpython demo: image.py.
socket client is also attached for your reference.

Ouyang

 socket server with wxpython ##

from Main import opj
import wx,string
class MMCS(wx.Frame):
def __init__(self):
self.bmp = wx.Image(opj('bitmaps/image.bmp'),
wx.BITMAP_TYPE_BMP)
self.bmp.SetMask(True)
wx.Frame.__init__(self, parent=None, title='monitoring system',
size=(500,600))
self.panel = wx.Panel(self,-1)

def monitor(self,x,y,angle):
bmp = self.bmp.Rotate(angle, (x,y), True,None)
bmp = bmp.ConvertToBitmap()

wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
bmp.GetHeight()))
del bmp

app = wx.PySimpleApp()
frame = MMCS()
frame.Show()
frame.monitor(50,10,0.0)
#app.MainLoop()

# Server program
from socket import *
# Set the socket parameters
host = "192.168.0.2"
port = 21567
buf = 1024
addr = (host,port)

# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)

# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"'"
 d = string.split(data, '-')

frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
if data == 'END':
print "end of moving the ship"

# Close socket
UDPSock.close()

# socket client ##>
rom socket import *
import time

# Set the socket parameters
host = "192.168.0.2"
port = 21567
buf = 1024
addr = (host,port)

# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg

# Send messages
while (1):
  for i in range(100):
   time.sleep(1)
   data = "50-100-%s"%(0.1*i)
   if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'."
# Close socket
UDPSock.close()

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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-07-30 Thread zxo102
Philippe,

Thanks a lot. I got the idea. Let me try it.

Ouyang

Philippe Martin 写道:

> Philippe Martin wrote:
>
> > zxo102 wrote:
> >
> >> Hi everyone,
> >> I am using a python socket server to collect data from a socket
> >> client and then control a image location ( wxpython) with the data,
> >> i.e. moving the image around in the wxpython frame.
> >>But  the "app.MainLoop()" in wxpython looks like conflicting with
> >> the "while 1:" in socket server. After I commented the
> >> "app.MainLoop()", everything is working except two things:
> >>  1. if I click anywhere on the screen with the mouse, the image is
> >> gong and only the empty frame( or panel) is left.
> >>  2. if I don't  touch anything, the image is being moved around but
> >> the previous images are left behind in the panel.
> >> I guess that may be caused by "app.MainLoop()" commented.
> >>Anybody knows how to make the two things work together? I really
> >> appreciate your help.
> >>My sample code is modified based on the wxpython demo: image.py.
> >> socket client is also attached for your reference.
> >>
> >> Ouyang
> >>
> >>  socket server with wxpython ##
> >>
> >> from Main import opj
> >> import wx,string
> >> class MMCS(wx.Frame):
> >> def __init__(self):
> >> self.bmp = wx.Image(opj('bitmaps/image.bmp'),
> >> wx.BITMAP_TYPE_BMP)
> >> self.bmp.SetMask(True)
> >> wx.Frame.__init__(self, parent=None, title='monitoring system',
> >> size=(500,600))
> >> self.panel = wx.Panel(self,-1)
> >>
> >> def monitor(self,x,y,angle):
> >> bmp = self.bmp.Rotate(angle, (x,y), True,None)
> >> bmp = bmp.ConvertToBitmap()
> >>
> >> wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
> >> bmp.GetHeight()))
> >> del bmp
> >>
> >> app = wx.PySimpleApp()
> >> frame = MMCS()
> >> frame.Show()
> >> frame.monitor(50,10,0.0)
> >> #app.MainLoop()
> >>
> >> # Server program
> >> from socket import *
> >> # Set the socket parameters
> >> host = "192.168.0.2"
> >> port = 21567
> >> buf = 1024
> >> addr = (host,port)
> >>
> >> # Create socket and bind to address
> >> UDPSock = socket(AF_INET,SOCK_DGRAM)
> >> UDPSock.bind(addr)
> >>
> >> # Receive messages
> >> while 1:
> >> data,addr = UDPSock.recvfrom(buf)
> >> if not data:
> >> print "Client has exited!"
> >> break
> >> else:
> >> print "\nReceived message '", data,"'"
> >>  d = string.split(data, '-')
> >>
> >> frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
> >> if data == 'END':
> >> print "end of moving the ship"
> >>
> >> # Close socket
> >> UDPSock.close()
> >>
> >> # socket client ##>
> >> rom socket import *
> >> import time
> >>
> >> # Set the socket parameters
> >> host = "192.168.0.2"
> >> port = 21567
> >> buf = 1024
> >> addr = (host,port)
> >>
> >> # Create socket
> >> UDPSock = socket(AF_INET,SOCK_DGRAM)
> >> def_msg = "===Enter message to send to server===";
> >> print "\n",def_msg
> >>
> >> # Send messages
> >> while (1):
> >>   for i in range(100):
> >>time.sleep(1)
> >> data = "50-100-%s"%(0.1*i)
> >> if(UDPSock.sendto(data,addr)):
> >> print "Sending message '",data,"'."
> >> # Close socket
> >> UDPSock.close()
> >
> >
> > If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
> > You need to have you server in a separate thread.
> >
> > Philippe
> PS:
> 
> http://wiki.wxpython.org/index.cgi/LongRunningTasks

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

Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-08-01 Thread zxo102
ker.abort()

def OnResult(self, event):
"""Show Result status."""
if event.data is None:
# Thread aborted (using our convention of None return)
self.status.SetLabel('Computation aborted')
else:
# Process results here
self.status.SetLabel('Computation Result: %s-%s-%s' %
(event.data[0], event.data[1],event.data[2]))
angle = event.data[2]
x = event.data[0]
y = event.data[1]
bmp = self.bmp.Rotate(angle, (x,y), True,None)
bmp = bmp.ConvertToBitmap()
wx.StaticBitmap(self.panel, -1, bmp, (x, y),
(bmp.GetWidth(), bmp.GetHeight()))
# In either event, the worker is done
self.worker = None

class MainApp(wx.App):
"""Class Main App."""
def OnInit(self):
"""Init Main App."""
self.frame = MainFrame(None, -1)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True

if __name__ == '__main__':
app = MainApp(0)
app.MainLoop()

##



Philippe Martin 写道:

> Philippe Martin wrote:
>
> > zxo102 wrote:
> >
> >> Hi everyone,
> >> I am using a python socket server to collect data from a socket
> >> client and then control a image location ( wxpython) with the data,
> >> i.e. moving the image around in the wxpython frame.
> >>But  the "app.MainLoop()" in wxpython looks like conflicting with
> >> the "while 1:" in socket server. After I commented the
> >> "app.MainLoop()", everything is working except two things:
> >>  1. if I click anywhere on the screen with the mouse, the image is
> >> gong and only the empty frame( or panel) is left.
> >>  2. if I don't  touch anything, the image is being moved around but
> >> the previous images are left behind in the panel.
> >> I guess that may be caused by "app.MainLoop()" commented.
> >>Anybody knows how to make the two things work together? I really
> >> appreciate your help.
> >>My sample code is modified based on the wxpython demo: image.py.
> >> socket client is also attached for your reference.
> >>
> >> Ouyang
> >>
> >>  socket server with wxpython ##
> >>
> >> from Main import opj
> >> import wx,string
> >> class MMCS(wx.Frame):
> >> def __init__(self):
> >> self.bmp = wx.Image(opj('bitmaps/image.bmp'),
> >> wx.BITMAP_TYPE_BMP)
> >> self.bmp.SetMask(True)
> >> wx.Frame.__init__(self, parent=None, title='monitoring system',
> >> size=(500,600))
> >> self.panel = wx.Panel(self,-1)
> >>
> >> def monitor(self,x,y,angle):
> >> bmp = self.bmp.Rotate(angle, (x,y), True,None)
> >> bmp = bmp.ConvertToBitmap()
> >>
> >> wx.StaticBitmap(self.panel, -1, bmp, (x, y), (bmp.GetWidth(),
> >> bmp.GetHeight()))
> >> del bmp
> >>
> >> app = wx.PySimpleApp()
> >> frame = MMCS()
> >> frame.Show()
> >> frame.monitor(50,10,0.0)
> >> #app.MainLoop()
> >>
> >> # Server program
> >> from socket import *
> >> # Set the socket parameters
> >> host = "192.168.0.2"
> >> port = 21567
> >> buf = 1024
> >> addr = (host,port)
> >>
> >> # Create socket and bind to address
> >> UDPSock = socket(AF_INET,SOCK_DGRAM)
> >> UDPSock.bind(addr)
> >>
> >> # Receive messages
> >> while 1:
> >> data,addr = UDPSock.recvfrom(buf)
> >> if not data:
> >> print "Client has exited!"
> >> break
> >> else:
> >> print "\nReceived message '", data,"'"
> >>  d = string.split(data, '-')
> >>
> >> frame.monitor(string.atoi(d[0]),string.atoi(d[1]),string.atof(d[2]))
> >> if data == 'END':
> >> print "end of moving the ship"
> >>
> >> # Close socket
> >> UDPSock.close()
> >>
> >> # socket client ##>
> >> rom socket import *
> >> import time
> >>
> >> # Set the socket parameters
> >> host = "192.168.0.2"
> >> port = 21567
> >> buf = 1024
> >> addr = (host,port)
> >>
> >> # Create socket
> >> UDPSock = socket(AF_INET,SOCK_DGRAM)
> >> def_msg = "===Enter message to send to server===";
> >> print "\n",def_msg
> >>
> >> # Send messages
> >> while (1):
> >>   for i in range(100):
> >>time.sleep(1)
> >> data = "50-100-%s"%(0.1*i)
> >> if(UDPSock.sendto(data,addr)):
> >> print "Sending message '",data,"'."
> >> # Close socket
> >> UDPSock.close()
> >
> >
> > If you get rid of app.MaiLoop(), you basically get rid of all GUI events.
> > You need to have you server in a separate thread.
> >
> > Philippe
> PS:
> 
> http://wiki.wxpython.org/index.cgi/LongRunningTasks

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

after an image is moved to a new location, how to delete the image at the old location?

2006-08-01 Thread zxo102
Hi everyone,
 As shown in the code below (modified based on the Image.py in
wxpython demo), an image is created at location 1:  (50,10) with
rotated angle 1.12.  Now, suppose I got another set of new data, I want
to move the image to location 2:  (166,400) with rotated angle 1.5.
case 1:
 if I use
 "wx.StaticBitmap(panel, -1, bmp2, (166, 400), (bmp2.GetWidth(),
bmp2.GetHeight()))",
 everything is fine but I don't know how to delete the image at
location 1.
case 2:
 If I use
 "kk.SetBitmap(bmp2)" (see the code below),
 the rotated image (angle 1.5) is put to location 1: (50,10)
instead of location 2: (166,400). Or I don't know how to move the image
to the new location (166,400).

anybody knows how to solve the above problem?  Thanks  a lot.

Ouyang


#
def runTest(frame, nb, log):
bmp = wx.Image(opj('bitmaps/image.bmp'), wx.BITMAP_TYPE_BMP)
bmp.SetMask(True)

# image.bmp is originally located in (50,10) with rotated angle
1.12
x = 50
y = 10
angle = 1.12
bmp1 = bmp.Rotate(angle, (x,y), True,None)
bmp1 = bmp1.ConvertToBitmap()
panel = wx.Panel(nb, -1)

kk = wx.StaticBitmap(panel, -1, bmp1, (x, y), (bmp1.GetWidth(),
bmp1.GetHeight()))

   # Now image.bmp is  relocated at (166,400) with rotated angle 1.5

x= 166
y = 400
angle = 1.5
bmp2 = bmp.Rotate(angle, (x,y), True,None)
bmp2 = bmp2.ConvertToBitmap()
wx.StaticBitmap(panel, -1, bmp2, (x,y), (bmp2.GetWidth(),
bmp2.GetHeight()))

#kk.SetBitmap(bmp2)

return panel
###3

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


Re: how to make python socket server work with the app.MainLoop() in wxpython?

2006-08-08 Thread zxo102
Dennis:

Thanks for your message. Let me try the double-buffer-operation.

Ouyang
Dennis Lee Bieber wrote:
> On 1 Aug 2006 01:10:18 -0700, "zxo102" <[EMAIL PROTECTED]> declaimed the
> following in comp.lang.python:
>
> >
> > I just wrote the code following the example you provided. The image
> > location can be controlled with the data from socket client. But only
> > one thing confuse me. When the image keeps moving to a new location,
> > the image at a "old" location is not deleted and  is left behind in the
> > frame. Do you know what is going on with it?  The location of image  is
> > processed in "def OnResult(self,event):" and is initialized in "def
> > __init__(self, parent, id):" of "class MainFrame" ( See the code
> > attached).
> >
>   Off hand, it is doing just what the code says it should.
>
>   Each time you update position, you are COPYING a SMALL rectangle
> (the "moved" image) into the larger frame... Only the pixels
> corresponding to the small rectangle are changed -- anything that was
> already in the frame stays there.
>
>   You might want to double-buffer the operations...
>
>   For each move:
>   clear an unseen "frame-sized" buffer
>   compute the new location of the "moved" image
>   blit the "moved" image into the unseen buffer
>   blit the full unseen buffer to the viewed frame (not to a
> portion of the frame, but replace the entire frame contents)
>
>   The double-buffer is to avoid annoying the viewer with the "flash"
> of clearing out the view frame before drawing the new image
>
> --
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/

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


draw an image in wx.BufferedDC onto the page created by AddPage of wx.Notebook

2006-08-10 Thread zxo102
Hi everyone,
   I have tried two days to figure out how to draw the image in
wx.BufferedDC on the page created by AddPage of wx.Notebook but still
got no clue.

   The attached example works fine. If I click the menu "Draw" --> "New
Drawing". The image with wx.BufferedDC/wx.BufferedPaintDC can move
around on the frame. But If I uncomment those three commented lines in
"class TestFrame" to add a new page (from wx.Notebook) with a tag and
modify the last line like
self.Window = DrawWindow(form2)
I can not see the image from wx.BufferedDC anywhere and don't know what
is going on.

 I need your help. Thanks a lot.


The attached example is based on the example on the site:
   http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing

ouyang


import wx
import random
import os,time

USE_BUFFERED_DC = 1

def opj(path):
"""Convert paths to the platform-specific separator"""
str = apply(os.path.join, tuple(path.split('/')))
# HACK: on Linux, a leading / gets lost...
if path.startswith('/'):
str = '/' + str
return str


class BufferedWindow(wx.Window):
def __init__(self, parent, id,
 pos = wx.DefaultPosition,
 size = wx.DefaultSize,
 style=wx.NO_FULL_REPAINT_ON_RESIZE):
wx.Window.__init__(self, parent, id, pos, size, style)

self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_SIZE, self.OnSize)

self.bmp0 = wx.Image(opj('image.bmp'), wx.BITMAP_TYPE_BMP)
self.bmp0.SetMask(True)
self.bmp = self.bmp0.Rotate(1.1215, (50,10), True,None)
self.bmp = self.bmp.ConvertToBitmap()
self.x = 100
self.y = 100
self.angle = 0.0
self.OnSize(None)

def Draw(self,dc):
pass

def OnPaint(self, event):
if USE_BUFFERED_DC:
dc = wx.BufferedPaintDC(self, self._Buffer)
else:
dc = wx.PaintDC(self)
dc.DrawBitmap(self._Buffer,0,0)

def OnSize(self,event):
self.Width, self.Height = self.GetClientSizeTuple()
self._Buffer = wx.EmptyBitmap(self.Width, self.Height)
self.UpdateDrawing()

def SaveToFile(self,FileName,FileType):
self._Buffer.SaveFile(FileName,FileType)

def UpdateDrawing(self):
if USE_BUFFERED_DC:
 dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer)
 self.Draw(dc)
else:
# update the buffer
dc = wx.MemoryDC()
dc.SelectObject(self._Buffer)

self.Draw(dc)
# update the screen
wx.ClientDC(self).Blit(0, 0, self.Width, self.Height, dc,
0, 0)

class DrawWindow(BufferedWindow):
def __init__(self, parent, id = -1):
BufferedWindow.__init__(self, parent, id)

def Draw(self, dc):
dc.BeginDrawing()
dc.SetBackground( wx.Brush("White") )
dc.Clear() # make sure you clear the bitmap!
bmp = self.bmp0.Rotate(self.angle, (self.x,self.y), True,None)
bmp = bmp.ConvertToBitmap()
dc.DrawBitmap(bmp, self.x,self.y, True)
dc.EndDrawing()

class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "Double Buffered Test",
 wx.DefaultPosition,
 size=(500,500),
 style=wx.DEFAULT_FRAME_STYLE |
wx.NO_FULL_REPAINT_ON_RESIZE)

MenuBar = wx.MenuBar()
file_menu = wx.Menu()
ID_EXIT_MENU = wx.NewId()
file_menu.Append(ID_EXIT_MENU, "E&xit","Terminate the program")
self.Bind(wx.EVT_MENU, self.OnQuit, id=ID_EXIT_MENU)
MenuBar.Append(file_menu, "&File")

draw_menu = wx.Menu()
ID_DRAW_MENU = wx.NewId()
draw_menu.Append(ID_DRAW_MENU, "&New Drawing","Update the
Drawing Data")
self.Bind(wx.EVT_MENU, self.NewDrawing, id=ID_DRAW_MENU)
BMP_ID = wx.NewId()
draw_menu.Append(BMP_ID,'&Save Drawing\tAlt-I','')
self.Bind(wx.EVT_MENU, self.SaveToFile, id=BMP_ID)
MenuBar.Append(draw_menu, "&Draw")

self.SetMenuBar(MenuBar)

#nb = wx.Notebook(self, -1)
#form2 = Form2(nb, -1)
#nb.AddPage(form2, "Sizers")

self.Window = DrawWindow(self)

def OnQuit(self,event):
self.Close(True)

def NewDrawing(self,event):
if event==None:
 self.Window.UpdateDrawing()
else:
self.Window.y = 100
for i in range(10):
   time.sleep(1)
   self.Window.y = self.Window.y + 5
   self.Window.angle = self.Window.angle+0.1*1
   self.Window.UpdateDrawing()

def SaveToFile(self,event):
dlg = wx.FileDialog(self, "Choose a file name to save the image
as a PNG to",
   defaultDir = "",
   defaultFile = "",
   wildcard = "*.png",
   style=wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
 

start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread zxo102
Hi,
   I am doing a small project using socket server and thread in python.
 This is first time for me to use socket and thread things.
   Here is my case. I have 20 socket clients.  Each client send a set
of sensor data per second to a socket server.  The socket server will
do two things: 1. write data into a file via bsddb; 2. forward the data
to a GUI written in wxpython.
   I am thinking the code should work as follow (not sure it is
feasible)
  20 threads, each thread takes care of a socket server with a
different port.
   I want all socket servers start up and wait for client connection.
In the attached demo code, It stops at the startup of first socket
server somewhere in the following two lines and waits for client call:

   lstn.listen(5)
   (clnt,ap) = lstn.accept()

  Any ideas how to handle these 20 clients?  Really appreciate your
suggestions.

Thanks a lot.

Ouyang


import socket
import sys
import threading
class srvr(threading.Thread):
   v = ''
   vlock = threading.Lock()
   id = 0  # next available thread number
   def __init__(self,clntsock):
  threading.Thread.__init__(self)
  self.myid = srvr.id
  srvr.id += 1
  self.myclntsock = clntsock
   def run(self):
  while 1:
 k = self.myclntsock.recv(1)
 if k == '': break
 # update v in an atomic manner
 srvr.vlock.acquire()
 srvr.v += k
 srvr.vlock.release()
 self.myclntsock.send(srvr.v)
  self.myclntsock.close()

#lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#port = int(sys.argv[1])  # server port number
#lstn.bind(('', port))
#lstn.listen(5)
nclnt = 20
mythreads = []  # list of all the threads

for i in range(nclnt):
   lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   lstn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   lstn.bind(('', 2000+i+1))
   lstn.listen(5)
   (clnt,ap) = lstn.accept()
   s = srvr(clnt)
   mythreads.append(s)
   s.start()

# shut down the server socket, since it's not needed anymore
#lstn.close()

# wait for all threads to finish
for s in mythreads:
   s.join()

print 'the final value of v is', srvr.v

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


Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread zxo102
Jean-Paul,
Thanks a lot. The code is working. The python twisted is new to me too.
Here are my three more questions:
1. Since the code need to be started in a wxpyhon GUI (either by
clicking a button or up with the GUI),  do I have to run the code in a
thread (sorry, I have not tried it yet)?
2. How can I grab the client data in the code? Can you write two lines
for that? I really appreciate that.
3. After I change
self.transport.write(''.join(self.data))
   to
self.transport.write(''.join(data))
  and scan all the ports with the following code twice (run twice).
First round scanning says "succefully connected". But second round
scanning says "failed". I have to restart your demo code to make it
work.

Ouyang


import sys, threading, socket

class scanner(threading.Thread):
   tlist = []  # list of all current scanner threads
   maxthreads = int(sys.argv[2])  # max number of threads we're
allowing
   evnt = threading.Event()  # event to signal OK to create more
threads
   lck =  threading.Lock()  # lock to guard tlist
   def __init__(self,tn,host):
  threading.Thread.__init__(self)
  #self.threadnum = tn  # thread ID/port number
  self.threadnum = 2000+tn  # thread ID/port number
  self.host = host  # checking ports on this host
   def run(self):
  s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  try:
 s.connect((self.host, self.threadnum))
 print "%d:  successfully connected" % self.threadnum
 s.close()
  except:
 print "%d:  connection failed" % self.threadnum
  # thread is about to exit; remove from list, and signal OK if we
  # had been up against the limit
  scanner.lck.acquire()
  scanner.tlist.remove(self)
  print "%d:  now active --" % self.threadnum, scanner.tlist
  if len(scanner.tlist) == scanner.maxthreads-1:
 scanner.evnt.set()
 scanner.evnt.clear()
  scanner.lck.release()
   def newthread(pn,hst):
  scanner.lck.acquire()
  sc = scanner(pn,hst)
  scanner.tlist.append(sc)
  scanner.lck.release()
  sc.start()
  print "%d:  starting check" % pn
  print "%d:  now active --" % pn, scanner.tlist
   newthread = staticmethod(newthread)

def main():
   host = sys.argv[1]
   #for i in range(1,100):
   for i in range(20):
  scanner.lck.acquire()
  print "%d:  attempting check" % i
  # check to see if we're at the limit before starting a new thread
  if len(scanner.tlist) >= scanner.maxthreads:
 # too bad, need to wait until not at thread limit
 print "%d:  need to wait" % i
 scanner.lck.release()
 scanner.evnt.wait()
  else:
 scanner.lck.release()
  scanner.newthread(i,host)
   for sc in scanner.tlist:
  sc.join()

if __name__ == '__main__':
main()






Jean-Paul Calderone 写道:

> On 12 Aug 2006 09:00:02 -0700, zxo102 <[EMAIL PROTECTED]> wrote:
> >Hi,
> >   I am doing a small project using socket server and thread in python.
> > This is first time for me to use socket and thread things.
> >   Here is my case. I have 20 socket clients.  Each client send a set
> >of sensor data per second to a socket server.  The socket server will
> >do two things: 1. write data into a file via bsddb; 2. forward the data
> >to a GUI written in wxpython.
> >   I am thinking the code should work as follow (not sure it is
> >feasible)
> >  20 threads, each thread takes care of a socket server with a
> >different port.
> >   I want all socket servers start up and wait for client connection.
> >In the attached demo code, It stops at the startup of first socket
> >server somewhere in the following two lines and waits for client call:
> >
>
> Threads aren't the best way to manage the concurrency present in this
> application.  Instead, consider using non-blocking sockets with an
> event notification system.  For example, using Twisted, your program
> might look something like this:
>
> from twisted.internet import reactor, protocol, defer
>
> class CumulativeEchoProtocol(protocol.Protocol):
> def connectionMade(self):
> # Stop listening on the port which accepted this connection
> self.factory.port.stopListening()
>
> # Set up a list in which to collect the bytes which we receive
> self.received = []
>
>
> def connectionLost(self, reason):
> # Notify the main program that this connection has been lost, so
> # that it can exit the process when there are no more connections.
> self.factory.onConnectionLost.callback(self)
>
> def dataReceived(self, data):
> # Accumulate the new data in our list
> self.received.append(data)
>

Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread zxo102
Jean-Paul,
I just start to learn Twisted. Here is my simple case: I can find
the data sent by clients in dataReceived but I don't know which
client/which port the data is from. After I know where the data comes
from, I can do different things there, for example, write them into
different files via bsddb.  I am not sure if it is the correct way to
do it.


   def dataReceived(self, data):
   # Accumulate the new data in our list
   self.received.append(data)
   # And then echo the entire list so far back to the client
   self.transport.write(''.join(data))

   print "> data: ", data
   print " which Port? : ", self.factory.port  # unforunately it is
an object here.

   # if Port == 2001:
   #   write the data into a file via bsddb
   # if Port == 2002:
   #   write the data into another file via bsddb
   #  etc .


Ouyang

Jean-Paul Calderone 写道:

> On 12 Aug 2006 10:44:29 -0700, zxo102 <[EMAIL PROTECTED]> wrote:
> >Jean-Paul,
> >Thanks a lot. The code is working. The python twisted is new to me too.
> >Here are my three more questions:
> >1. Since the code need to be started in a wxpyhon GUI (either by
> >clicking a button or up with the GUI),  do I have to run the code in a
> >thread (sorry, I have not tried it yet)?
>
> You can try to use Twisted's wxPython integration support:
>
> http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto15
>
> But note the warnings about how well it is likely to work.  Using a separate
> thread might be the best solution.
>
> >2. How can I grab the client data in the code? Can you write two lines
> >for that? I really appreciate that.
>
> I'm not sure what you mean.  The data is available in the `received' attribute
> of the protocol instance.  Any code which needs to manipulate the data can get
> that list and do whatever it likes with it.
>
> >3. After I change
> >self.transport.write(''.join(self.data))
> >   to
> >self.transport.write(''.join(data))
> >  and scan all the ports with the following code twice (run twice).
> >First round scanning says "succefully connected". But second round
> >scanning says "failed". I have to restart your demo code to make it
> >work.
>
> I intentionally added code which shuts the server off after the first round
> of connections is completed, since that seemed to be what your example
> program was doing.  If you don't want this, just remove the shutdown code.
> 
> Jean-Paul

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

why the method get() of python Queue is hang on there?

2006-08-14 Thread zxo102
Hi,
   I am using Queue from python2.4. Here is what happen to me:

import Queue
b = Queue.Queue(0)
b.put()
b.get()   # this is ok, it pops out 
b.get()   # this one does not return anything and is hang on there

Anybody knows what is going on with the second b.get()?

ouyang

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


Re: why the method get() of python Queue is hang on there?

2006-08-14 Thread zxo102
Thanks for your guys. I got it.  I thought  Queue can be used anywhere
in the code and the second b.get() would return a "None".

Ouyang


zxo102 写道:

> Hi,
>I am using Queue from python2.4. Here is what happen to me:
>
> import Queue
> b = Queue.Queue(0)
> b.put()
> b.get()   # this is ok, it pops out 
> b.get()   # this one does not return anything and is hang on there
> 
> Anybody knows what is going on with the second b.get()?
> 
> ouyang

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

Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-15 Thread zxo102
Bryan,
   Thanks for your note. Finally, I have made "one listener socket for
all the connections" work plus Queue-communication between the threads
in wxpython Gui and the threads for socket connections.
Trying to make that twisted example code in this topic for "one
listener socket-all the connections" but failed. That twisted example
only accepts one client connection. I have printed out the Twisted help
file (256 pages). Too much to read.

Ouyang


Bryan Olson 写道:

> zxo102 wrote:
> >I am doing a small project using socket server and thread in python.
> >  This is first time for me to use socket and thread things.
> >Here is my case. I have 20 socket clients.  Each client send a set
> > of sensor data per second to a socket server.  The socket server will
> > do two things: 1. write data into a file via bsddb; 2. forward the data
> > to a GUI written in wxpython.
> >I am thinking the code should work as follow (not sure it is
> > feasible)
> >   20 threads, each thread takes care of a socket server with a
> > different port.
> >I want all socket servers start up and wait for client connection.
> > In the attached demo code, It stops at the startup of first socket
> > server somewhere in the following two lines and waits for client call:
> >
> >lstn.listen(5)
> >(clnt,ap) = lstn.accept()
>
> It will block there, waiting for connection.
>
> >   Any ideas how to handle these 20 clients?  Really appreciate your
> > suggestions.
>
> One reserved port for each client strikes me as whacked,
> as does coding a server to handle exactly 20 of them. Since
> you say this is your first socket server, maybe you just
> haven't seen the usual techniques.
>
> Normally, one listener socket accepts all the connections.
> Each call to accept() returns a new, independent socket for the
> connection. You can then start a thread to handle the new
> socket. Untested:
>
>
>listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>listener.bind(('', 2000))
>listener.listen(5)
>while True: # or some should_continue() thing
>sock, _ = listener.accept()
>thread.start_new_thread(service_function, (sock,))
># Or start threads via class Threading
>
>
> To update the GUI, you could use the Queue from the Python
> library, and call wxPostEvent to tell the GUI go wake up and
> check the queue.
> 
> 
> -- 
> --Bryan

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

Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-15 Thread zxo102
"That twisted example  only accepts one client connection"  if only one
port is available.


zxo102 写道:

> Bryan,
>Thanks for your note. Finally, I have made "one listener socket for
> all the connections" work plus Queue-communication between the threads
> in wxpython Gui and the threads for socket connections.
> Trying to make that twisted example code in this topic for "one
> listener socket-all the connections" but failed. That twisted example
> only accepts one client connection. I have printed out the Twisted help
> file (256 pages). Too much to read.
>
> Ouyang
>
>
> Bryan Olson 写道:
>
> > zxo102 wrote:
> > >I am doing a small project using socket server and thread in python.
> > >  This is first time for me to use socket and thread things.
> > >Here is my case. I have 20 socket clients.  Each client send a set
> > > of sensor data per second to a socket server.  The socket server will
> > > do two things: 1. write data into a file via bsddb; 2. forward the data
> > > to a GUI written in wxpython.
> > >I am thinking the code should work as follow (not sure it is
> > > feasible)
> > >   20 threads, each thread takes care of a socket server with a
> > > different port.
> > >I want all socket servers start up and wait for client connection.
> > > In the attached demo code, It stops at the startup of first socket
> > > server somewhere in the following two lines and waits for client call:
> > >
> > >lstn.listen(5)
> > >(clnt,ap) = lstn.accept()
> >
> > It will block there, waiting for connection.
> >
> > >   Any ideas how to handle these 20 clients?  Really appreciate your
> > > suggestions.
> >
> > One reserved port for each client strikes me as whacked,
> > as does coding a server to handle exactly 20 of them. Since
> > you say this is your first socket server, maybe you just
> > haven't seen the usual techniques.
> >
> > Normally, one listener socket accepts all the connections.
> > Each call to accept() returns a new, independent socket for the
> > connection. You can then start a thread to handle the new
> > socket. Untested:
> >
> >
> >listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >listener.bind(('', 2000))
> >listener.listen(5)
> >while True:   # or some should_continue() thing
> >sock, _ = listener.accept()
> >thread.start_new_thread(service_function, (sock,))
> ># Or start threads via class Threading
> >
> >
> > To update the GUI, you could use the Queue from the Python
> > library, and call wxPostEvent to tell the GUI go wake up and
> > check the queue.
> > 
> > 
> > -- 
> > --Bryan

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

Is it possible to run two "while 1:" loops in two threadings respectively?

2007-07-16 Thread zxo102
Hi,
   I would like to combine two python applications into a single one
with two threadings. Both of them have a "while 1:" loop respectively.
For example, one application is to monitoring serial port 'com1' and
another application is a TCP/IP server which has used threadings
already. I write the following demo code but it does not work right.
It stays in the first "while 1:" and never thingOne.start(). The
second threading never be started.
Any ideas?

Thanks a lot.

Ouyang
#
import threading, time
class serial_port_com1:
  def spc(self):
 i = 0
 while 1:
time.sleep(5)
print "%d: hello, I am here in spc()"%i
i += 1

class TCP_IP:
  def tcpip(self):
 i = 0
 while 1:
time.sleep(5)
print "%d: hello, I am here in tcpip()"%i
i += 1

class ThreadOne ( threading.Thread ):
   def run ( self ):
  print 'Thread', self.getName(), 'started.'
  time.sleep ( 5 )
  print 'Thread', self.getName(), 'ended.'

class ThreadTwo ( threading.Thread ):
   def run ( self ):
  print 'Thread', self.getName(), 'started.'
  thingOne.join()
  print 'Thread', self.getName(), 'ended.'

if __name__=="__main__":
   spc  = serial_port_com1()
   tcpip = TCP_IP()
   thingOne = ThreadOne(target=spc.spc())
   thingOne.start()
   thingTwo = ThreadTwo(target=tcpip.tcpip())
   thingTwo.start()

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

Re: Is it possible to run two "while 1:" loops in two threadings respectively?

2007-07-18 Thread zxo102
On 7 17 ,   3 01 , "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> zxo102 schrieb:
>
>
>
>
>
> > Hi,
> >I would like to combine two python applications into a single one
> > with two threadings. Both of them have a "while 1:" loop respectively.
> > For example, one application is to monitoring serial port 'com1' and
> > another application is a TCP/IP server which has used threadings
> > already. I write the following demo code but it does not work right.
> > It stays in the first "while 1:" and never thingOne.start(). The
> > second threading never be started.
> > Any ideas?
>
> > Thanks a lot.
>
> > Ouyang
> > #
> > import threading, time
> > class serial_port_com1:
> >   def spc(self):
> >  i = 0
> >  while 1:
> >time.sleep(5)
> >print "%d: hello, I am here in spc()"%i
> >i += 1
>
> > class TCP_IP:
> >   def tcpip(self):
> >  i = 0
> >  while 1:
> >time.sleep(5)
> >print "%d: hello, I am here in tcpip()"%i
> >i += 1
>
> > class ThreadOne ( threading.Thread ):
> >def run ( self ):
> >   print 'Thread', self.getName(), 'started.'
> >   time.sleep ( 5 )
> >   print 'Thread', self.getName(), 'ended.'
>
> > class ThreadTwo ( threading.Thread ):
> >def run ( self ):
> >   print 'Thread', self.getName(), 'started.'
> >   thingOne.join()
> >   print 'Thread', self.getName(), 'ended.'
>
> > if __name__=="__main__":
> >spc  = serial_port_com1()
> >tcpip = TCP_IP()
> >thingOne = ThreadOne(target=spc.spc())
> >thingOne.start()
> >thingTwo = ThreadTwo(target=tcpip.tcpip())
> >thingTwo.start()
>
> There are several problems here. First of all, one either subclasses
> Thread and implements run - then your code should look like this:
>
> class ThreadTwo(Thread):
>def run(self):
>  tcpip.tcpip()
>
> Or you don't subclass Thread and pass a target. But that target must be
> a function. You don't pass a function, you call it!!
>
> Look at this:
>
> Thread(target=tcpip.tcpip)
>
> Note the missing parentheses!
>
> Apart from that, you should seriously consider applying a consistent
> naming style to your code.
>
> Diez- -
>
> - -

Diez,
   Thanks for your reply. I have tried the both you suggested. First
one works and second one does not. I am using "subclass thread" way to
implement my application. Thanks a lot.
ouyang

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


Help: GIS

2007-08-02 Thread zxo102
Hi,
I am new in GIS area and need your suggestions for where I can
start from.  I have a python based web application with a database.
Now I would like to add a GIS map into my application. When a user
clicks a certain area in the GIS map, it can grab the data from the
database via my python based application. Do I have to use MapServer
or Grass or some other  backends for this purpose?
   Thanks  a lot.

Ouyang

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

Re: Help: GIS

2007-08-03 Thread zxo102
On 8 3 ,   9 34 , [EMAIL PROTECTED] wrote:
> On Aug 2, 10:46 pm, zxo102 <[EMAIL PROTECTED]> wrote:
>
> > Hi,
> > I am new in GIS area and need your suggestions for where I can
> > start from.  I have a python based web application with a database.
> > Now I would like to add a GIS map into my application. When a user
> > clicks a certain area in the GIS map, it can grab the data from the
> > database via my python based application. Do I have to use MapServer
> > or Grass or some other  backends for this purpose?
> >Thanks  a lot.
>
> > Ouyang
>
> While I am not a part of our GIS department, they use ArcGIS which has
> Python support built in. If that's what you're using, you should be
> able to use the examples given on ESRI's 
> website:http://www.spatialvision.com.au/html/tips-python-arc9.htm
>
> Hmmm...not much there. Here are some other links I found:
>
> http://nrm.salrm.uaf.edu/~dverbyla/arcgis_python/index.htmlhttp://www.ollivier.co.nz/publication/uc2004/python_workshop/sld008.htmhttp://www.3dartist.com/WP/python/pycode.htm
>
> I don't know if these will be much help. You really need to just dig
> in and start coding. I would recommend "Programming Python 3rd Ed." by
> Lutz if you want something in hard copy. "Dive Into Python" is a free
> book that's online that I'm told is very good. Both have good
> examples, some of which are involved. All the web oriented Python
> books are a few years old, but the code in them still works, for the
> most part.
>
> Mike

Mike, Thanks for your suggestion. I am looking for a python GIS
package (without any other GIS backends like mapserver) which can be
simply imported into my current python web application. I am not sure
if it is available. So far, the close one I found is Python
Cartographic Lab. But I can not find any examples for PCL. Anyway, I
am still on the way of the deep learning curve for GIS.

Ouyang
Ouyang

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


py2exe: LoadLibrary(pythondll) failed

2007-03-03 Thread zxo102
Hi there,
   I py2exe my test.py  as test.exe with a lot of dll and pyc in that
directory. If I move the test.exe into another directory and run it
from there, it gives me an error " LoadLibrary(pythondll) failed...
python24.dll".  How can I set it up correctly for this test.exe to
run?   Thanks.

Ouyang

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

Re: py2exe: LoadLibrary(pythondll) failed

2007-03-03 Thread zxo102
On 3月4日, 上午6时50分, Thomas Heller <[EMAIL PROTECTED]> wrote:
> zxo102 schrieb:
>
> > Hi there,
> >I py2exe my test.py  as test.exe with a lot of dll and pyc in that
> > directory. If I move the test.exe into another directory and run it
> > from there, it gives me an error " LoadLibrary(pythondll) failed...
> > python24.dll".  How can I set it up correctly for this test.exe to
> > run?   Thanks.
>
> > Ouyang
>
> The test.exe created by py2exe relies on everything else in the dist 
> directory,
> so you must copy these files as well.
>
> Thomas

Thanks. Let me try it.

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

How to display Chinese in a list retrieved from database via python

2008-12-24 Thread zxo102
Hi,
   I retrieve some info in Chinese from postgresql  and assign it to a
variable 'info' defined in javascript of a html page:
   var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
\xc4']
  But I want it to be
   var info = ['中文','中文','中文']
 since in html pages (via javascript), the items in chinese out of the
former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can
not be displayed correctly when it is inserted into a html page. If
the list is  var info = ['中文','中文','中文'] , then everything works
fine.

 Anybody knows how to solve this problem?

Thanks in advance.


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


Re: How to display Chinese in a list retrieved from database via python

2008-12-25 Thread zxo102
On 12月25日, 下午3时35分, "Chris Rebert"  wrote:
> On Wed, Dec 24, 2008 at 11:29 PM, zxo102  wrote:
> > Hi,
> >   I retrieve some info in Chinese from postgresql  and assign it to a
> > variable 'info' defined in javascript of a html page:
> >   var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
> > \xc4']
> >  But I want it to be
> >   var info = ['中文','中文','中文']
> >  since in html pages (via javascript), the items in chinese out of the
> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can
> > not be displayed correctly when it is inserted into a html page. If
> > the list is  var info = ['中文','中文','中文'] , then everything works
> > fine.
>
> >  Anybody knows how to solve this problem?
>
> Upgrading to Python 2.6 would probably be beneficial due to its better
> handling of Unicode.
> Also, posting some of the actual code you're using (to generate
> JavaScript, I guess?) would definitely help.
>
> Merry Christmas,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

Hi Chris:

I have to use python2.4 since many other python packages have not been
updated to 2.6.
Here is my demo:
I create a table in postgresql:

 create table my_table (
id   serial,
name char(20),
phone char(20)
 );

and insert two records into the table
(4, '中文', '133499555')
(5, '中文', '3434343434343')


I would like to generate a html page dynamically, here is the demo
script


def do_search(a):
 # 调用ODBC模块
 import odbc
 # 通过ODBC中的"my_odbc"和相应的数据库建立连接
 cc = odbc.odbc('dsn=wisco')
 cursor1 = cc.cursor()
 # 将数据存入数据库中的"my_table"
 #cursor1.execute("select * from my_table where name = '%s' "%a)
 cursor1.execute("select * from my_table where name like '%%%s%%'
"%a)
 rr = cursor1.fetchall()
 # 显示用户查到的数据
 row01 = rr[0]
 row02 = rr[1]
 print row01, row02
 html_str = ''
 #print "Content-Type: text/html\n\n"
 html_str += "  test  \n"
 html_str += "\n"
 html_str += " var row01 = %s\n"
 html_str += " var row02 = %s\n"
 html_str += "\n"
 html_str += " \n"
 html_str = html_str%(row01,row02)
 f = open('c:\\xbop_sinopec\\apache\\htdocs\\test01.html','w')
 f.write(html_str)
 f.close

do_search('中文')
#

The html code is as follows

  test 

 var row01 = (1, '\xd6\xd0\xce\xc4', '133499555')
 var row02 = (2, '\xd6\xd0\xce\xc4', '3434343434343')

 

But the '中文' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called
from somewhere,
'\xd6\xd0\xce\xc4' can not be displayed correctly as '中文' in html
environment.

Thanks for your help and Merry Christmas to you too.

ouyang


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


Re: How to display Chinese in a list retrieved from database via python

2008-12-25 Thread zxo102
On 12月26日, 上午4时58分, "Gabriel Genellina" 
wrote:
> En Thu, 25 Dec 2008 07:27:03 -0200, zxo102  escribió:
>
>
>
> > On 12月25日, 下午3时35分, "Chris Rebert"  wrote:
> >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102  wrote:
> >> > Hi,
> >> >   I retrieve some info in Chinese from postgresql  and assign it to a
> >> > variable 'info' defined in javascript of a html page:
> >> >   var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
> >> > \xc4']
> >> >  But I want it to be
> >> >   var info = ['中文','中文','中文']
> >> >  since in html pages (via javascript), the items in chinese out of the
> >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] can
> >> > not be displayed correctly when it is inserted into a html page. If
> >> > the list is  var info = ['中文','中文','中文'] , then everything works
> >> > fine.
>
> > The html code is as follows
>
> >   test 
> > 
> >  var row01 = (1, '\xd6\xd0\xce\xc4', '133499555')
> >  var row02 = (2, '\xd6\xd0\xce\xc4', '3434343434343')
> > 
> >  
>
> > But the '中文' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called
> > from somewhere,
> > '\xd6\xd0\xce\xc4' can not be displayed correctly as '中文' in html
> > environment.
>
> You forgot to specify the page encoding, gb2312 presumably. If adding the  
> encoding does not help, I'd say the problem must reside on how you later  
> use row01 and row02 (your html page does not those variables for  
> anything). '中文' is the same as '\xd6\xd0\xce\xc4', and both javascript  
> and Python share the same representation for strings (mostly) so this  
> should not be an issue.
>
> My PC is unable to display those characters, but I get "true" from this:
>
>  test 
>  language=javascript>alert('中文'=='\xd6\xd0\xce\xc4')
>
> --
> Gabriel Genellina

I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4') displays 
> some "junks". I am thinking there may be some way to convert 
> '\xd6\xd0\xce\xc4' to '中文' in the list with python before I generate the html 
> page. As a result, when I open the html file with Vi, I can see '中文' directly 
> instead of  '\xd6\xd0\xce\xc4'. That will solve my problem.

Any ideas?

Ouyang

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


Re: How to display Chinese in a list retrieved from database via python

2008-12-26 Thread zxo102
On 12月26日, 下午3时16分, "Mark Tolonen"  wrote:
> "zxo102"  wrote in message
>
> news:979fdf6d-0500-47ba-87fd-0f0361ca3...@p2g2000prf.googlegroups.com...
>
>
>
>
>
> > On 12月26日, 上午4时58分, "Gabriel Genellina" 
> > wrote:
> >> En Thu, 25 Dec 2008 07:27:03 -0200, zxo102  escribió:
>
> >> > On 12月25日, 下午3时35分, "Chris Rebert"  wrote:
> >> >> On Wed, Dec 24, 2008 at 11:29 PM, zxo102  wrote:
> >> >> > Hi,
> >> >> >   I retrieve some info in Chinese from postgresql  and assign it to
> >> >> > a
> >> >> > variable 'info' defined in javascript of a html page:
> >> >> >   var info = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
> >> >> > \xc4']
> >> >> >  But I want it to be
> >> >> >   var info = ['中文','中文','中文']
> >> >> >  since in html pages (via javascript), the items in chinese out of
> >> >> > the
> >> >> > former :['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4']
> >> >> > can
> >> >> > not be displayed correctly when it is inserted into a html page. If
> >> >> > the list is  var info = ['中文','中文','中文'] , then everything
> >> >> > works
> >> >> > fine.
>
> >> > The html code is as follows
>
> >> >   test 
> >> > 
> >> >  var row01 = (1, '\xd6\xd0\xce\xc4', '133499555')
> >> >  var row02 = (2, '\xd6\xd0\xce\xc4', '3434343434343')
> >> > 
> >> >  
>
> >> > But the '中文' is '\xd6\xd0\xce\xc4'. When row01 and row02 is called
> >> > from somewhere,
> >> > '\xd6\xd0\xce\xc4' can not be displayed correctly as '中文' in html
> >> > environment.
>
> >> You forgot to specify the page encoding, gb2312 presumably. If adding the
> >> encoding does not help, I'd say the problem must reside on how you later
> >> use row01 and row02 (your html page does not those variables for
> >> anything). '中文' is the same as '\xd6\xd0\xce\xc4', and both javascript
> >> and Python share the same representation for strings (mostly) so this
> >> should not be an issue.
>
> >> My PC is unable to display those characters, but I get "true" from this:
>
> >>  test 
> >>  >> language=javascript>alert('中文'=='\xd6\xd0\xce\xc4')
>
> >> --
> >> Gabriel Genellina
>
> > I did that: , but it does not work. Alert('\xd6\xd0\xce\xc4')
> >> displays some "junks". I am thinking there may be some way to convert
> >> '\xd6\xd0\xce\xc4' to '中文' in the list with python before I generate
> >> the html page. As a result, when I open the html file with Vi, I can see
> >> '中文' directly instead of  '\xd6\xd0\xce\xc4'. That will solve my
> >> problem.
>
> > Any ideas?
>
> Use charset=gb2312 instead of charset='gb2312'(remove single quotes).
>
> I was able to display 中文 successfully with this code:
>
> f=open('test.html','wt')
> f.write('''
> 
> test
> \xd6\xd0\xce\xc4''')
> f.close()
>
> -Mark- 隐藏被引用文字 -
>
> - 显示引用的文字 -

Mark,
   I have exactly copied your code into the htdocs of my Apache
server,



test
\xd6\xd0\xce\xc4

but it still shows me \xd6\xd0\xce\xc4. Any ideas?

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


Re: How to display Chinese in a list retrieved from database via python

2008-12-28 Thread zxo102
On 12月27日, 下午4时08分, "Gabriel Genellina" 
wrote:
> En Sat, 27 Dec 2008 03:03:24 -0200,zxo102 escribió:
>
>
>
> > On 12月26日, 下午3时16分, "Mark Tolonen"   
> > wrote:
>
> >> I was able to display 中文 successfully with this code:
>
> >> f=open('test.html','wt')
> >> f.write('''
> >> 
> >> test
> >> \xd6\xd0\xce\xc4''')
> >> f.close()
>
> > Mark,
> >    I have exactly copied your code into the htdocs of my Apache
> > server,
>
> > 
> > 
> > test
> > \xd6\xd0\xce\xc4
>
> > but it still shows me \xd6\xd0\xce\xc4. Any ideas?
>
> That's not the same thing as Mark T. said.
> The original was Python code to *write* a test file that you could open in
> a browser. Things like "\xd6\xd0" are escape sequences interpreted by
> Python, not meant to literally appear in a file. Like \n -- it means
> "start a new line", one wants a new line in the output, *not* a backslash
> and a letter n. "\xd6\xd0" generate *two* bytes, not eight. If the file is  
> interpreted as containing latin-1 characters, you see them as ÖÐ. But due  
> to the "charset=gb2312" line, those two bytes together make the ideograph  
> 中.
>
> So, write the Python code (from f=open... up to f.close()) in a file and
> execute it. Then open the generated test.html file. You should see the two
> ideographs.
>
> --
> Gabriel Genellina

Thanks for your explanation. The example works now. It is close to my
real case.

I have a list in a dictionary and want to insert it into the html
file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I
can see "中文" in CASE 1 but that is not what I want. CASE 2 does not
show me correct things.
So, in CASE 3, I hacked the script of CASE 2 with a function:
conv_list2str() to 'convert' the list into a string. CASE 3 can show
me "中文". I don't know what is wrong with CASE 2 and what is right with
CASE 3.

Without knowing why, I have just hard coded my python application
following CASE 3 for displaying Chinese characters from a list in a
dictionary in my web application.

Any ideas?

Happy a New Year: 2009

ouyang



CASE 1:

f=open('test.html','wt')
f.write('''

test

var test = ['\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4', '\xd6\xd0\xce
\xc4']
alert(test[0])
alert(test[1])
alert(test[2])


''')
f.close()

CASE 2:
###
mydict = {}
mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
\xc4']
f_str = '''

test

var test = %(JUNK)s
alert(test[0])
alert(test[1])
alert(test[2])


'''

f_str = f_str%mydict
f=open('test02.html','wt')
f.write(f_str)
f.close()

CASE 3:
###
mydict = {}
mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
\xc4']

f_str = '''

test

var test = %(JUNK)s
alert(test[0])
alert(test[1])
alert(test[2])


'''

import string

def conv_list2str(value):
   list_len = len(value)
   list_str = "["
   for ii in range(list_len):
   list_str += '"'+string.strip(str(value[ii])) + '"'
   if ii != list_len-1:
 list_str += ","
   list_str += "]"
   return list_str

mydict['JUNK'] = conv_list2str(mydict['JUNK'])

f_str = f_str%mydict
f=open('test03.html','wt')
f.write(f_str)
f.close()
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to display Chinese in a list retrieved from database via python

2008-12-29 Thread zxo102
On 12月29日, 下午5时06分, "Mark Tolonen"  wrote:
> "zxo102"  wrote in message
>
> news:2560a6e0-c103-46d2-aa5a-8604de4d1...@b38g2000prf.googlegroups.com...
>
> > I have a list in a dictionary and want to insert it into the html
> > file. I test it with following scripts of CASE 1, CASE 2 and CASE 3. I
> > can see "中文" in CASE 1 but that is not what I want. CASE 2 does not
> > show me correct things.
> > So, in CASE 3, I hacked the script of CASE 2 with a function:
> > conv_list2str() to 'convert' the list into a string. CASE 3 can show
> > me "中文". I don't know what is wrong with CASE 2 and what is right with
> > CASE 3.
>
> > Without knowing why, I have just hard coded my python application
> > following CASE 3 for displaying Chinese characters from a list in a
> > dictionary in my web application.
>
> > Any ideas?
>
> See below each case...新年快乐!
>
>
>
> > Happy a New Year: 2009
>
> > ouyang
>
> > CASE 1:
> > 
> > f=open('test.html','wt')
> > f.write('''
> > 
> > test
> > 
> > var test = ['\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4', '\xd6\xd0\xce
> > \xc4']
> > alert(test[0])
> > alert(test[1])
> > alert(test[2])
> > 
> > 
> > ''')
> > f.close()
>
> In CASE 1, the *4 bytes* D6 D0 CE C4 are written to the file, which is the
> correct gb2312 encoding for 中文.
>
>
>
> > CASE 2:
> > ###
> > mydict = {}
> > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
> > \xc4']
> > f_str = '''
> > 
> > test
> > 
> > var test = %(JUNK)s
> > alert(test[0])
> > alert(test[1])
> > alert(test[2])
> > 
> > 
> > '''
>
> > f_str = f_str%mydict
> > f=open('test02.html','wt')
> > f.write(f_str)
> > f.close()
>
> In CASE 2, the *16 characters* "\xd6\xd0\xce\xc4" are written to the file,
> which is NOT the correct gb2312 encoding for 中文, and will be interpreted
> however javascript pleases.  This is because the str() representation of
> mydict['JUNK'] in Python 2.x is the characters "['\xd6\xd0\xce\xc4',
> '\xd6\xd0\xce\xc4', '\xd6\xd0\xce\xc4']".
>
>
>
> > CASE 3:
> > ###
> > mydict = {}
> > mydict['JUNK'] = ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce
> > \xc4']
>
> > f_str = '''
> > 
> > test
> > 
> > var test = %(JUNK)s
> > alert(test[0])
> > alert(test[1])
> > alert(test[2])
> > 
> > 
> > '''
>
> > import string
>
> > def conv_list2str(value):
> >   list_len = len(value)
> >   list_str = "["
> >   for ii in range(list_len):
> >   list_str += '"'+string.strip(str(value[ii])) + '"'
> >   if ii != list_len-1:
> >list_str += ","
> >   list_str += "]"
> >   return list_str
>
> > mydict['JUNK'] = conv_list2str(mydict['JUNK'])
>
> > f_str = f_str%mydict
> > f=open('test03.html','wt')
> > f.write(f_str)
> > f.close()
>
> CASE 3 works because you build your own, correct, gb2312 representation of
> mydict['JUNK'] (value[ii] above is the correct 4-byte sequence for 中文).
>
> That said, learn to use Unicode strings by trying the following program, but
> set the first line to the encoding *your editor* saves files in.  You can
> use the actual Chinese characters instead of escape codes this way.  The
> encoding used for the source code and the encoding used for the html file
> don't have to match, but the charset declared in the file and the encoding
> used to write the file *do* have to match.
>
> # coding: utf8
>
> import codecs
>
> mydict = {}
> mydict['JUNK'] = [u'中文',u'中文',u'中文']
>
> def conv_list2str(value):
> return u'["' + u'","'.join(s for s in value) + u'"]'
>
> f_str = u'''
> 
> test
> 
> var test = %s
> alert(test[0])
> alert(test[1])
> alert(test[2])
> 
> 
> '''
>
> s = conv_list2str(mydict['JUNK'])
> f=codecs.open('test04.html','wt',encoding='gb2312')
> f.write(f_str % s)
> f.close()
>
> -Mark
>
> P.S.  Python 3.0 makes this easier for what you want to do, because the
> representation of a dictionary changes.  You'll be able to skip the
> conv_list2str() function and all strings are Unicode by default.

Thanks for your comments, Mark. I understand it now. The list(escape
codes): ['\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4','\xd6\xd0\xce\xc4'] is
from a postgresql database with "select" statement.I will postgresql
database configurations and see if it is possible to return ['中文','中
文','中文'] directly with "select" statement.

ouyang

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


pyserial: failed to readlines() after many hours running.

2008-10-11 Thread zxo102
Hello All,

I have a system. An instrument attched to 'com1' is wireless connected
to many sensors at different locations.  The instrument can forward
the  "commands" (from pyserial's write()) to those sensors.  Based on
the "commands",  the sensors keep sending corresponding data back to
the instrument which wraps up those data and put into "com1" . The
readlines() of pyserial pick up those data for processing.
The data ’string' does not have "\n".

With the following pythong script, if timeout = 0.1,  ser.readlines()
in thread1 failed to receive any data after approximate 20 hours. if
timeout=0.5,  ser.readlines() in thread1 failed to receive any data
after approximate 60 hours.  I am not sure the thread1 was dead or
not. But the whole script did not throw out any error information and
ser.write() in thread2 was ok and kept sending "commands" to com1.

I am testing "timeout = 1" right now, it will probably take more days
to fail to receive data.

Anybody knows how long I should set for "timeout"?  Since the data are
from different sensors, I have no idea when they arrive at com1 via
that instrument. If the timeout is set too long,  com1 (com1 has
buffer? Sorry, I don't know very much about hardwares) can not have
enough buffer to hold those coming data before ser.readlines(). Or how
does ser.readlines() work?

Should I use readline() instead of readlines()?

Thanks for your any help in advance.

The below is the script:


In thread 1:

import serial, time

ser=serial.Serial('com1', baudrate=9600, bytesize=8, parity='N',
stopbits=1, timeout=0.1,xonxoff=0, rtscts=0)

while 1:
 reading = ser.readlines()
 for i in range(len(reading)):
   if len(reading[i]) > 0:
aa = map(ord, reading[i])
bb = ["%02X"%aa[k] for k in range(len(aa))]
# do something here
  else:
pass
 time.sleep(ReadComSleepTime)
ser.close()

In thread 2:
...
while 1:
 ...
 ser.write("some commands here")
 ...
 time.sleep(30)



Best Regards

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


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread zxo102
On 10月11日, 下午11时00分, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On2008-10-11,zxo102<[EMAIL PROTECTED]> wrote:
>
> > I have a system. An instrument attched to 'com1' is wireless connected
> > to many sensors at different locations.  The instrument can forward
> > the  "commands" (from pyserial's write()) to those sensors.  Based on
> > the "commands",  the sensors keep sending corresponding data back to
> > the instrument which wraps up those data and put into "com1" . The
> > readlines() of pyserial pick up those data for processing.
> > The data ?string' does not have "\n".
>
> If the data you're reading doesn't contain "\n", then you can't
> use readline() or readlines().
>
> --
> Grant Edwards   grante Yow! I smell a RANCID
>   at   CORN DOG!
>visi.com

But readlines() can read data out of 'com1' for many hours. Maybe I
should try read().

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


Re: pyserial: failed to readlines() after many hours running.

2008-10-11 Thread zxo102
On 10月12日, 上午1时13分, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Unknown wrote:
> > On2008-10-11,zxo102<[EMAIL PROTECTED]> wrote:
>
> >> I have a system. An instrument attched to 'com1' is wireless connected
> >> to many sensors at different locations.  The instrument can forward
> >> the  "commands" (from pyserial's write()) to those sensors.  Based on
> >> the "commands",  the sensors keep sending corresponding data back to
> >> the instrument which wraps up those data and put into "com1" . The
> >> readlines() of pyserial pick up those data for processing.
> >> The data ?string' does not have "\n".
>
> Do you have the option of having the instrument insert them between
> readings?
>
>
>
> > If the data you're reading doesn't contain "\n", then you can't
> > use readline() or readlines().
>
> Use .read() instead.

I can not have the instrument insert "\n" between readings. That is
out of my control. I can try read(). Thanks.

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


Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?

2008-05-24 Thread zxo102
Hi,
   how  to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to
"\xED\x6F\x3C\x01" in python coding?
When I take 'ED6F3C01' as a string and insert '\x' into it, I just got
the error information : invalid \x escape.
   Thanks.

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


Re: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?

2008-05-24 Thread zxo102
But this is not "\xED\x6F\x3C\x01".  I need it for
struct.unpack('f',"\xED\x6F\x3C\x01") to calculate the decimal value
(IEEE 754).
Any other suggestions?

ouyang

On 5月25日, 上午6时46分, Sebastian 'lunar' Wiesner <[EMAIL PROTECTED]>
wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> [ zxo102 <[EMAIL PROTECTED]> ]
>
> >how  to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to
> > "\xED\x6F\x3C\x01" in python coding?
> > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got
> > the error information : invalid \x escape.
>
> [1]--> 'ED6F3C01'.decode('hex')
> Out[1]: '\xedo<\x01'
>
> - --
> Freedom is always the freedom of dissenters.
>   (Rosa Luxemburg)
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.9 (GNU/Linux)
>
> iEYEARECAAYFAkg4mtEACgkQn3IEGILecb7W6ACeNwr/vavkaXluvc0zeSa4cy1N
> YFIAoJjMsrRcLhqAPRxKktUqt7miMTrs
> =jxll
> -END PGP SIGNATURE-

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

Re: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?

2008-05-24 Thread zxo102
On 5月25日, 上午6时59分, zxo102 <[EMAIL PROTECTED]> wrote:
> But this is not "\xED\x6F\x3C\x01".  I need it for
> struct.unpack('f',"\xED\x6F\x3C\x01") to calculate the decimal value
> (IEEE 754).
> Any other suggestions?
>
> ouyang
>
> On 5月25日, 上午6时46分, Sebastian 'lunar' Wiesner <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > -BEGIN PGP SIGNED MESSAGE-
> > Hash: SHA1
>
> > [ zxo102 <[EMAIL PROTECTED]> ]
>
> > >how  to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to
> > > "\xED\x6F\x3C\x01" in python coding?
> > > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got
> > > the error information : invalid \x escape.
>
> > [1]--> 'ED6F3C01'.decode('hex')
> > Out[1]: '\xedo<\x01'
>
> > - --
> > Freedom is always the freedom of dissenters.
> >   (Rosa Luxemburg)
> > -BEGIN PGP SIGNATURE-
> > Version: GnuPG v2.0.9 (GNU/Linux)
>
> > iEYEARECAAYFAkg4mtEACgkQn3IEGILecb7W6ACeNwr/vavkaXluvc0zeSa4cy1N
> > YFIAoJjMsrRcLhqAPRxKktUqt7miMTrs
> > =jxll
> > -END PGP SIGNATURE-- 隐藏被引用文字 -
>
> - 显示引用的文字 -

Hash: SHA1
I got it. Just simply use it like
struct.unpack('f',"ED6F3C01".decode('hex')). It works now.

Thank you very much.
ouyang
--
http://mail.python.org/mailman/listinfo/python-list

how to make smtplib.SMTP('localhost') work on window xp

2008-09-27 Thread zxo102
Hi,
 I am trying to use python module smtplib to send my email out on
window xp (localhost).

import smtplib
server = smtplib.SMTP('localhost')

but I got the error information as follows:

Traceback (most recent call last):
  File "", line 1, in ?
  File "c:\python24\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
  File "c:\python24\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
  File "c:\python24\lib\smtplib.py", line 355, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed

I am not sure what is wrong with it. Should I configure my window xp
somewhere to run smtplib.SMTP('localhost')?

Thanks in advance.

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


Re: how to make smtplib.SMTP('localhost') work on window xp

2008-09-29 Thread zxo102
On 9月29日, 下午2时53分, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message
> <[EMAIL PROTECTED]>, zxo102
> wrote:
>
> > SMTPServerDisconnected: Connection unexpectedly closed
>
> Does the SMTP server on localhost mention anything about the connection
> attempt in its log?
>
> If you telnet/netcat to port 25 on localhost, does anything interesting
> happen?

Thanks for your mentioning of the SMTP server on localhost. I did not
install that. After I install a free smtp server downloaded from
http://www.softstack.com/freesmtp.html,
and run the following python script again, everything is fine now.

import smtplib
server = smtplib.SMTP('localhost')
...

Thanks for your message.

ouyang


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

Re: how to make smtplib.SMTP('localhost') work on window xp

2008-09-29 Thread zxo102
On 9月29日, 下午7时29分, Steve Holden <[EMAIL PROTECTED]> wrote:
> zxo102 wrote:
> > Hi,
> >  I am trying to use python module smtplib to send my email out on
> > window xp (localhost).
>
> > import smtplib
> > server = smtplib.SMTP('localhost')
>
> > but I got the error information as follows:
>
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> >   File "c:\python24\lib\smtplib.py", line 244, in __init__
> > (code, msg) = self.connect(host, port)
> >   File "c:\python24\lib\smtplib.py", line 311, in connect
> > (code, msg) = self.getreply()
> >   File "c:\python24\lib\smtplib.py", line 355, in getreply
> > raise SMTPServerDisconnected("Connection unexpectedly closed")
> > SMTPServerDisconnected: Connection unexpectedly closed
>
> > I am not sure what is wrong with it. Should I configure my window xp
> > somewhere to run smtplib.SMTP('localhost')?
>
> > Thanks in advance.
>
> Well your code certainly expects *something* to be listening on port 25
> on localhost. It's fairly unusual to run an SMTP server on Windows XP,
> though not impossible.
>
> usually your email system is set up to use some external host as uts
> SMPT server: if you look in your mail client's configuration you will
> probably find out whihc host you should be using.
>
> regards
>  Steve
>
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/

In my case, I implement an application with python to accomplish
collecting real time data from a serial port: com1 which is connected
to some xbee hardwares.
The python logging module is used to save the information generated at
runtime into a log file. Since the site is far away from my office, I
try to
use a smtp server with the python smtplib module to send the log file
into my email account regularly so that I can check it from anywhere.

Thanks for your suggestion.

Ouyang

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

Help: why python odbc module can not fetch all over?

2006-03-22 Thread zxo102
Hi everyone,
I need your help for using python odbc module. I have a simple
table defined as

create table A (
  userId char(10),
  courseid char(10),
  grade  integer,
  primary key(userId,courseId)
)

  userIdcourseId   grade
 1  1001 50
 1  1002 89
 2  1001 90
 2  1002 98

  in SQL server. Now I run the following query in SQL server Query
Analyzer:

select userId, grade from A  group by grade, userId order by userId
DESC compute count(userId), sum(grade) by userId

and got the results in two parts for each user in the Query Analyzer:
The results are shown like the following pattern

userId grade  < part1 results for user 1
  .  1   50
 1   89
-
 cnt sum   <--- part2 result for user 1
  2   139
===
 userId grade <--- part1 results for user 2
   2  90
   2  98
---
  cnt  sum <--- part2 results for user 2
   2188


But when I use python odbc to fetch the results from the database in
SQL server, I can only get part1 of results for user 2. All other
results are gone, for example, part2 for user 2 and all for user 1.

userId grade  < part1 results for user 2
  .  290
 298

Here is what I did:
>>> import odbc
>>> cc = odbc.odbc('dsn=student_info')
>>> c2=cc.cursor()
>>> c2.execute("select userId, grade from A  group by grade, userId order by 
>>> userId DESC compute count(userId), sum(grade) by userId")
>>> r = c2.fetchall()
>>> print r
[('2', 90), ('2', 98)]

Any body knows what is going on with python odbc module and how to get
"cnt" and "sum" in part 2 and others?

Thanks for your help in advance. I really appreciate that.

Ouyang

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


Re: Help: why python odbc module can not fetch all over?

2006-03-23 Thread zxo102
Hi Dennis,

Thanks for your effort. I really appreciate it.  It works for me
now.

Ouyang

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


How to transfer a string from cgi at server side to a javascript function at client side as an argument?

2009-10-12 Thread zxo102
Hi everyone,
How can I transfer a string from a cgi at server side to a
javascript function at client side as an argument? Here is my case:

1. client side: javascript in html page:
...
mygrid = new dhtmlXGridObject('gridbox');
...
var cgi3 = "/bop-cgi/xbop";
cgi3 += "?requestIds=[wisco.mProducts.dboProducts.mySearch]";
cgi3 += "&wisco.mProducts.dboProducts.searchString=1=1";

mygrid.loadXML(cgi3);



2. server side cgi: wisco.mProducts.dboProducts.mySearch
...
def mySearch(self):
 self.search()
 row_count = self.response['rowCount']
 myStr = ""%
(row_count, 1)
for i in range(len(self.response['dbcCode'])):
a = self.response['dbcCode'][i]
   c = self.response['dbcId'][i]
myStr = myStr + ""
myStr = myStr + "" + a + ""
myStr = myStr + "%s"%c + ""
myStr = myStr + ""
myStr = myStr + ""
...
I want the myStr to be transferred to mygrid.loadXML like:

mygrid.loadXML('x')

Any ideas?

Thanks in advance for your help.

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


In python CGI, how to pass "hello" back to a javascript function as an argument at client side?

2009-10-12 Thread zxo102
Hi everyone,
How can I pass a string generated from python cgi at server side
to a
javascript function as an argument at client side?

Here is my case:

1. client side:
 "load" is a javascript function in a html page. It starts the
python CGI "test.py" via Apache:


...
load("test.py" );
...

...


 I want test.py to "return"  a "hello" back so the javascript function
load takes "hello" as argument like  load("hello").

2. server side: test.py
...
#!c:\python24\python.exe

def main():
   message = 'hello'
   #return message

main()
...

Any ideas?


Thanks in advance for your help.


ouyang

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