Re: How to write an API for a Python application?

2005-11-16 Thread dwelch
Gary Kshepitzki wrote:
> Hello
> I would like to create an API for a piece of Python code. The API is for use 
> by non Python code.
> It should support interaction in both directions, both accessing functions 
> on the API and the ability for the API to raise events on its client.
> What is the best way to do that?
> I though of doing it as a python COM server but I am not familiar with COM 
> and I saw that implementing a COM server with events in python is not 
> trivial for me.
> Is there a better (or simpler) solution?
> What are the common ways for doing that?
> 
> Any answer would be highly appreciated.
> Regards
> Gary 
> 
> 

You could try Elmer:
http://elmer.sourceforge.net/index.html

I'm sure you could create a callable library (.so, .dll, etc) with it.

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


Re: PyQt layout question: QScrollView and QGridLayout?

2005-11-17 Thread dwelch
Volker Lenhardt wrote:
> Phil Thompson schrieb:
> 
>> On Thursday 17 November 2005 2:56 pm, Volker Lenhardt wrote:
>>
>>> prefer to use QGridLayout, but cannot add it to the scroll view.
>>>
>>> sc=QScrollView(self)
>>> layout=QGridLayout(..., sc.viewport())
>>> sc.addChild(layout)
>>>
>>> results in a TypeError.
>>>
>>> Is there a way to get it to work? Filling a box viewport with lots of
>>> padding boxes and white space labels to establish grids is very
>>> cumbersome. And I need 4 different layouts to change places.
>>
>>
>>
>> QGridLayout is not a sub-class of QWidget, which is what addChild() is 
>> expecting. You probably want QGrid.
>>
>> Phil
> 
> 
> I hoped to find a more assuring answer. There's no MultiCellWidget, no 
> Col/RowStretching, no Col/RowSpacing in QGrid. I've got to patch up one 
> VBox with a whole bunch of QV/QHBoxes and QGrids not to mention the 
> white space QLabels to fill not used grid cells.
> 
> And I have to delete all of them to change to another data layout.
> 
> Are you sure that there's no way to fill a QScrollView with the help of 
> some QLayout?
> 
> Still hopefully
> Volker

I _think_ I have code that does waht you want. This creates multiple 
layouts that contain an icon, a button, and some text on a scrollview. 
The code is awkward and ugly, but it works.


class ScrollToolView(QScrollView):
 def __init__(self,parent = None,name = None,fl = 0):
 QScrollView.__init__(self,parent,name,fl)
 self.items = {}
 self.setStaticBackground(True)
 self.enableClipper(True)
 
self.viewport().setPaletteBackgroundColor(qApp.palette().color(QPalette.Active, 
QColorGroup.Background))
 self.row_height = 120

 def viewportResizeEvent(self, e):
 for x in self.items:
 self.items[x].resize(e.size().width(), self.row_height)

 def addItem(self, name, title, pix, text, button_text, button_func):
 num_items = len(self.items)
 LayoutWidget = QWidget(self.viewport(),"layoutwidget")
 LayoutWidget.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, 
QSizePolicy.Minimum))
 LayoutWidget.setGeometry(QRect(0, 0, self.width(), 
self.row_height))
 self.addChild(LayoutWidget)

 if num_items:
 self.moveChild(LayoutWidget, 0, self.row_height*num_items)

 layout = QGridLayout(LayoutWidget,1,1,10,10,"layout")

 pushButton = QPushButton(LayoutWidget,"pushButton")
 
pushButton.setSizePolicy(QSizePolicy(QSizePolicy.Maximum,QSizePolicy.Fixed,0,0,
 
pushButton.sizePolicy().hasHeightForWidth()))
 self.connect(pushButton,SIGNAL("clicked()"), button_func)

 layout.addWidget(pushButton,2,2)

 textLabel = QLabel(LayoutWidget,"textLabel")

 layout.addWidget(textLabel,1,1)

 pixmap = QLabel(LayoutWidget,"pixmapLabel2")
 
pixmap.setSizePolicy(QSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed,0,0,
  pixmap.sizePolicy().hasHeightForWidth()))
 pixmap.setMinimumSize(QSize(32,32))
 pixmap.setMaximumSize(QSize(32,32))
 pixmap.setPixmap(pix)
 pixmap.setScaledContents(1)

 layout.addWidget(pixmap,1,0)

 textLabel2 = QLabel(LayoutWidget,"textLabel2")
 textLabel2.setAlignment(QLabel.WordBreak | QLabel.AlignTop)
 
textLabel2.setSizePolicy(QSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding))

 layout.addWidget(textLabel2,2,1)

 if num_items:
 line = QFrame(LayoutWidget,"line")
 line.setFrameShadow(QFrame.Sunken)
 line.setFrameShape(QFrame.HLine)
 layout.addMultiCellWidget(line,0,0,0,2)

 textLabel.setText(title)
 textLabel2.setText(text)
 pushButton.setText(button_text)
 self.resizeContents(self.width(), num_items*self.row_height*2)

 LayoutWidget.show()

 try:
 self.items[name]
 except KeyError:
 self.items[name] = LayoutWidget
 else:
 print "ERROR: Duplicate button name:", name

 def clear(self):
 if len(self.items):
 for x in self.items:
 self.removeChild(self.items[x])
 self.items[x].hide()

 self.items.clear()
 self.resizeContents(self.width(), 0)



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


Re: newbie question concerning formatted output

2005-11-29 Thread dwelch
Thomas Liesner wrote:
> Hello all,
> 
> i am having some hard time to format the output of my small script. I am
> opening a file which containes just a very long string of hexdata
> seperated by spaces. Using split() i can split this string into single
> words and print them on stdout. So far so good. But i want to print always
> three of them in a single line and after that a linebreak.
> 
> So instead of:
> 
> 3905
> 3009
> 
> 4508
> f504
> 
> 3707
> 5a07
> 
> etc...
> 
> i'd like to have:
> 
> 3905 3009 
> 4508 f504 
> 3707 5a07 
> etc...
> 
> This is the codesnippet i am using:
> 
> #!/usr/bin/python
> 
> import string
> inp = open("xyplan.nobreaks","r")
> data = inp.read()
> for words in data.split():
> print words
> inp.close()
> 
> Any hints?
> 
> TIA,
> ./Tom


Might be more than you need, but I've employed "TextFormatter" 
(http://www.faqts.com/knowledge_base/view.phtml/aid/4517) to good effect.

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


Re: How to ping in Python?

2005-12-05 Thread dwelch
Nico Grubert wrote:
> Hi there,
> 
> I could not find any "ping" Class or Handler in python (2.3.5) to ping a 
> machine.
> I just need to "ping" a machine to see if its answering. What's the best 
> way to do it?
> 
> Kind regards,
> Nico


# Derived from ping.c distributed in Linux's netkit. That code is
# copyright (c) 1989 by The Regents of the University of California.
# That code is in turn derived from code written by Mike Muuss of the
# US Army Ballistic Research Laboratory in December, 1983 and
# placed in the public domain. They have my thanks.

# Bugs are naturally mine. I'd be glad to hear about them. There are
# certainly word-size dependenceies here.

# Copyright (c) Matthew Dixon Cowles, .
# Distributable under the terms of the GNU General Public License
# version 2. Provided with no warranties of any sort.

# Note that ICMP messages can only be sent from processes running
# as root.

# Revision history:
#
# November 22, 1997
# Initial hack. Doesn't do much, but rather than try to guess
# what features I (or others) will want in the future, I've only
# put in what I need now.
#
# December 16, 1997
# For some reason, the checksum bytes are in the wrong order when
# this is run under Solaris 2.X for SPARC but it works right under
# Linux x86. Since I don't know just what's wrong, I'll swap the
# bytes always and then do an htons().
#
# December 4, 2000
# Changed the struct.pack() calls to pack the checksum and ID as
# unsigned. My thanks to Jerome Poincheval for the fix.
#

# From /usr/include/linux/icmp.h; your milage may vary.
ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.

# I'm not too confident that this is right but testing seems
# to suggest that it gives the same answers as in_cksum in ping.c
def checksum(str):
 csum = 0
 countTo = (len(str) / 2) * 2
 count = 0
 while count < countTo:
 thisVal = ord(str[count+1]) * 256 + ord(str[count])
 csum = csum + thisVal
 csum = csum & 0xL # Necessary?
 count = count + 2

 if countTo < len(str):
 csum = csum + ord(str[len(str) - 1])
 csum = csum & 0xL # Necessary?

 csum = (csum >> 16) + (csum & 0x)
 csum = csum + (csum >> 16)
 answer = ~csum
 answer = answer & 0x

 # Swap bytes. Bugger me if I know why.
 answer = answer >> 8 | (answer << 8 & 0xff00)

 return answer

def receiveOnePing(mySocket, ID, timeout):
 timeLeft = timeout

 while 1:
 startedSelect = time.time()
 whatReady = select.select([mySocket], [], [], timeLeft)
 howLongInSelect = (time.time() - startedSelect)

 if whatReady[0] == []: # Timeout
 return -1

 timeReceived = time.time()
 recPacket, addr = mySocket.recvfrom(1024)
 icmpHeader = recPacket[20:28]
 typ, code, checksum, packetID, sequence = 
struct.unpack("bbHHh", icmpHeader)

 if packetID == ID:
 bytesInDouble = struct.calcsize("d")
 timeSent = struct.unpack("d", recPacket[28:28 + 
bytesInDouble])[0]
 return timeReceived - timeSent

 timeLeft = timeLeft - howLongInSelect

 if timeLeft <= 0:
 return -1

def sendOnePing(mySocket, destAddr, ID):
 # Header is type (8), code (8), checksum (16), id (16), sequence (16)
 myChecksum = 0

 # Make a dummy heder with a 0 checksum.
 header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, ID, 1)
 bytesInDouble = struct.calcsize("d")
 data = (192 - bytesInDouble) * "Q"
 data = struct.pack("d", time.time()) + data

 # Calculate the checksum on the data and the dummy header.
 myChecksum = checksum(header + data)

 # Now that we have the right checksum, we put that in. It's just easier
 # to make up a new header than to stuff it into the dummy.
 if prop.platform == 'darwin':
 myChecksum = socket.htons(myChecksum) & 0x
 else:
 myChecksum = socket.htons(myChecksum)

 header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0,
 myChecksum, ID, 1)

 packet = header + data
 mySocket.sendto(packet, (destAddr, 1)) # Don't know about the 1

def doOne(destAddr, timeout=10):
 # Returns either the delay (in seconds) or none on timeout.
 icmp = socket.getprotobyname("icmp")
 mySocket = socket.socket(socket.AF_INET,socket.SOCK_RAW,icmp)
 myID = os.getpid() & 0x
 sendOnePing(mySocket, destAddr, myID)
 delay = receiveOnePing(mySocket, myID, timeout)
 mySocket.close()

 return delay


def ping(host, timeout=1):
 dest = socket.gethostbyname(host)
 delay = doOne(dest, timeout)
 return delay

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


Re: pythonic exec* spawn*

2006-02-09 Thread dwelch
[EMAIL PROTECTED] wrote:
> You could possibly pickle an object and send it, but that could be a
> bit messy...
> 
pickle it (or shelve?) and then pass the pickle/shleve filename to the 
other process as a command line parameter?

Not sure if this would work or not, but that's where I would start.

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


Re: get Windows file type

2006-05-08 Thread dwelch
BartlebyScrivener wrote:
> Using Python on Windows XP, I am able to get almost all file and path
> info using os.path or stat, but I don't see a way to retrieve the file
> type? E.g. Microsoft Word file, HTML file, etc, the equivalent of what
> is listed in the "Type" column in the Windows Explorer box.
> 
> Thanks,
> 
> rick
> 
This worked well for me on Linux, should work on Windows:

http://www.demonseed.net/~jp/code/magic.py

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


Re: Handling yes/no questions from the User

2006-03-21 Thread dwelch
[EMAIL PROTECTED] wrote:
> I'm writing a scipt that need to interact with the user.
> Lets say I have the:
> 
> "Do you want to continue [Y|n]"
> 
> Where just pressing return means Yes (since its uppercase).
> 
> Its easy to write a function for this, but perhaps something like this
> already exists. Could someone point me to a class that handles this
> kind of user interaction?
> 
> BR / Claes
> 

I think a class would be overkill. I could see making this into a 
reusable function perhaps.

I just use some code like this (with the '*' indicating the default):

ok = False
while True:
 user_input = raw_input("\nUse this file (y=yes*, n=no, q=quit) 
?").strip().lower()

 if not user_input or user_input == 'y':
 ok = True
 break

 elif user_input == 'q':
 print "Exiting."
 sys.exit(0)

 elif user_input == 'n':
 break

 else:
 print "Please enter 'y', 'n', or 'q'"


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


Re: Probelem about image size and dimensions

2006-03-23 Thread dwelch
[EMAIL PROTECTED] wrote:
> I got a piece of python script to upload file and it can upload it to
> different folders on server depend on the type of file is image or not.
> but I also want to restrict the size and dimensions of file if it is a
> image file.Could anyone help me out?
> 
> 
> Parameter List:id, file, title='',folder
> 
> REQUEST=context.REQUEST
> content_type=file.headers['Content-Type']
> if content_type.find('image')!=-1: #.find() is a method in Python2.0<
> 
> 
> destination=context.restrictedTraverse('/cheng/rvdpas/uploadImage/'+folder)
> destination.manage_addImage(id, file, title)\
> 
> 
> else:
> 
> destination=context.restrictedTraverse('/cheng/rvdpas/uploadDocument/'+folder)
> destination.manage_addFile(id, file, title)
> 
> 
> return 'Finished'
> 

You could try this to get the image dimensions:


http://www.python.org/pypi?%3Aaction=search&name=ImageSize&version=&summary=&description=&keywords=&_pypi_hidden=0

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


A SANE scanner backend written in Python?

2006-03-28 Thread dwelch
I've read many times on this newsgroup over the years that you can write 
"just about anything" in Python, except perhaps a full operating system 
(maybe even that...?). So, with this spirit in mind, I would like to try 
to write a SANE scanner backend that I need to write, in Python rather 
than C. This work is being done on Linux using Python 2.4.2.

If you are not familar with SANE, and the SANE API, it basically boils 
down to supplying a libsane-.so shared library 
that supports a basic C interface. Example sane API calls into a backend 
are: sane_init(), sane_open(), sane_start(), sane_read() and 
sane_cancel(). At runtime, a backend is loaded up and its C interface is 
called to determine what devices are supported by the backend, to set 
options, and to actually perform a scan.

Obviously, this is an example of embedding Python, albiet with a 
different end result. I have not found any examples in the wild that 
embed Python in a shared library (vs. a standalone executable).

My trials so far have been fruitless. To start with, I simply took an 
outline of a shared library that defined all the relevant SANE APIs, 
linked it with SANE and Python, and placed a PyInitialize() in the 
sane_init() function. This immediately results in a segmentation fault. 
I'm not sure how to proceed from here. How would a separate .py file be 
accessed in this way and how would I call "back" into Python code when a 
C API was called? Is there going to be a problem of maintaining "state" 
in Python between invocations of the C API?

I've also explored using Elmer for this task, but have not had luck so 
far. Its also not clear to me whether this tool is appropriate for this 
task.

So, what I'd be interested in knowing is whether this is a foolish 
venture, or if I just have the wrong approach.

Any thoughts would be appreciated.

Thanks,

-Don


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