Remote askopenfilename()

2007-01-02 Thread half . italian
Hi all.

I'm trying to get Tkinter.askopenfilename() to list a directory tree on
a remote computer.  I've got some ideas, but nothing is slapping me in
the face.  Can someone point me in the right direction?

~Sean

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


Re: Using PIL to find separator pages

2007-05-31 Thread half . italian
On May 31, 10:01 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> I have a project that I wanted to solicit some advice
> on from this group.  I have millions of pages of scanned
> documents with each page in and individual .JPG file.
> When the documents were scanned the people that did
> the scanning put a colored (hot pink) separator page
> between the individual documents.  I was wondering if
> there was any way to utilize PIL to scan through the
> individual files, look at some small section on the
> page, and determine if it is a separator page by
> somehow comparing the color to the separator page
> color?  I realize that this would be some sort of
> percentage match where 100% would be a perfect match
> and any number lower would indicate that it was less
> likely that it was a coverpage.
>
> Thanks in advance for any thoughts or advice.
>
> Regards,
> Larry Bates

I used GraphicsMagick for a similar situation.  Once installed you can
run `gm identify' to return all sorts of usefull information about the
images.  In my case I had python call 'gm' to identify the number of
colors in each image, then inspect the output and handle the image
accordingly.  I'll bet PIL could do a similar thing, but in my case I
was examining DPX files which PIL can't handle.  Either approach will
most likely take a bit of time unless you spread the work over several
machines.

~Sean

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


get_traceback

2007-06-04 Thread half . italian
Hi,

Is there a function or idoim for returning an exception/traceback
rather than just printing it to stdout?  I'm running a deamon where
stdout is going to /dev/null, and I'm not even watching it..until
now.  All the functions I found in traceback and sys seemed only to
print the error rather than just returning it, so I resorted to this:

def get_traceback():
import traceback, tempfile
stdout = sys.stdout

f = tempfile.TemporaryFile(mode='w+')
sys.stdout = f

traceback.print_tb(sys.exc_info()[2])
error = f.read()
f.close()

sys.stdout = stdout
return error

Whats the right function?!?  Thanks.

~Sean

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


Re: get_traceback

2007-06-04 Thread half . italian
On Jun 4, 3:51 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Mon, 04 Jun 2007 14:23:00 -0300, <[EMAIL PROTECTED]> escribió:
>
> > Is there a function or idoim for returning an exception/traceback
> > rather than just printing it to stdout?  I'm running a deamon where
> > stdout is going to /dev/null, and I'm not even watching it..until
> > now.  All the functions I found in traceback and sys seemed only to
> > print the error rather than just returning it, so I resorted to this:
>
> Read again the docs for the traceback module.
> Maybe you are looking for traceback.format_exception(*sys.exc_info()) or  
> traceback.format_exc()
>
> >f = tempfile.TemporaryFile(mode='w+')
> >sys.stdout = f
> >traceback.print_tb(sys.exc_info()[2])
>
> In this case you can use StringIO instead of a temporary file, and the  
> file argument to print_tb instead of swapping sys.stdout
>
> --
> Gabriel Genellina

Thanks Gabriel.  That was exactly what I was looking for.  Also, I'm
glad to make a connection to the StringIO class.  I'm sure I will
remember it the next time I need it.

~Sean

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

Re: Who uses Python?

2007-06-06 Thread half . italian
On Jun 4, 1:47 pm, Mark Carter <[EMAIL PROTECTED]> wrote:
> walterbyrd wrote:
> > Anything else? Finance? Web-analytics? SEO? Digital art?
>
> I played with NodeBox a little while 
> ago:http://nodebox.net/code/index.php/Home
> "NodeBox is a Mac OS X application that lets you create 2D visuals
> (static, animated or interactive) using Python programming code and
> export them as a PDF or a QuickTime movie. NodeBox is free and
> well-documented."
>
> Pretty trippy stuff.

Thanks for the link.  Neato.

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


ftplib error- Large file

2007-06-06 Thread half . italian
Hi all,

I'm using ftplib to transfer large files to remote sites.  The process
seems to work perfectly with small files, but when the file gets to
large ~20GB I begin getting errors that sometimes seem to be non-
fatal, and other times the transfer does not complete.  I've debugged
the hell out of the code, and can't figure out what is going on..is it
the remote site?  Packet loss?

Traceback (most recent call last):

  File "/usr/local/sw/bin/FTPput.py", line 142, in execute
self.ftp.put(file.path)

  File "/usr/local/sw/lib/FTPconn.py", line 32, in put
return self.storbinary("STOR %s" % destfile, open(f.path, 'rb'))

  File "/usr/lib/python2.2/ftplib.py", line 422, in storbinary
return self.voidresp()

  File "/usr/lib/python2.2/ftplib.py", line 222, in voidresp
resp = self.getresp()

  File "/usr/lib/python2.2/ftplib.py", line 208, in getresp
resp = self.getmultiline()

  File "/usr/lib/python2.2/ftplib.py", line 194, in getmultiline
line = self.getline()

  File "/usr/lib/python2.2/ftplib.py", line 181, in getline
line = self.file.readline()

IOError: [Errno 104] Connection reset by peer

I'd appreciate any input or ideas.

~Sean

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


Re: ftplib error- Large file

2007-06-07 Thread half . italian
On Jun 6, 11:21 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>  <[EMAIL PROTECTED]> wrote:
> > Hi all,
>
> > I'm using ftplib to transfer large files to remote sites.  The process
> > seems to work perfectly with small files, but when the file gets to
> > large ~20GB I begin getting errors that sometimes seem to be non-
> > fatal, and other times the transfer does not complete.  I've debugged
> > the hell out of the code, and can't figure out what is going on..is it
> > the remote site?  Packet loss?
>
> 20 gig is a big thing - what is your link speed, and how long does the thing
> run before falling over - Is your ISP maybe giving you or the remote site a
> new IP addy periodically?  
>
> Are there any "anti jabber" precautions taken anywhere?
>
> you may have to break it up into smaller chunks and glue them together
> remotely...
>
> hth - Hendrik

It's different sites (state to state) within the same company, so I'm
sure of the IP addresses.  Whats odd is that the transfers don't fail
most of the time.  The transfer usually completes properly but
ftplib.FTP.storbinary() throws an IOError at the end of the file
instead of returning the status of the transfer.  I've resorted to
just catching and logging the exception and then comparing remote vs.
local md5's to check for integrity, but it seems like if a connection
error occurs, storbinary should handle the error and return an error
code rather than throwing an exception.  The 20gb files take about an
hour to transfer, and I've had success with files up to 60gb so far...
once I figured out what ftplib was doing and starting cathing the
IOError.

Why would storbinary throw an exception even when the file transfer
was successful?  Why would the exception not be thrown until after the
file was sent?  Shouldn't ftplib return something like (104,
"Connection reset by peer") instead of throwing an error?  Is my
reasoning off somewhere?

~Sean


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


Re: get a list from a string

2007-06-07 Thread half . italian
On Jun 7, 3:34 am, simon kagwe <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a string "distances = [[1,1,1,1],[2,2,2,2]]". I want to create a
> variable called distances whose value is the list [[1,1,1,1],[2,2,2,2]]. How 
> can
> I go about that? I know I can use setattr, but how do I create the list from 
> the
> string?
>
> Regards,
> Simon

exec("distances = [[1,1,1,1],[2,2,2,2]]")

~Sean

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


Re: ftplib error- Large file

2007-06-07 Thread half . italian
On Jun 7, 8:54 am, Facundo Batista <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Why would storbinary throw an exception even when the file transfer
> > was successful?  Why would the exception not be thrown until after the
> > file was sent?  Shouldn't ftplib return something like (104,
> > "Connection reset by peer") instead of throwing an error?  Is my
> > reasoning off somewhere?
>
> There was an error, the connection was reset by peer. The error code is
> 104. As it *was* an error, an exception is correct.
>
> You always can hide it yourself, with try/except...
>
> Regards,
>
> --
> .   Facundo
> .
> Blog:http://www.taniquetil.com.ar/plog/
> PyAr:http://www.python.org/ar/

Ok.  I guess that makes sense.  But what about the other
questions...mainly: Why would it throw an exception even though the
file was properly transferred?

I guess this could be blamed on the FTP server.

~Sean

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


Re: launching default browser

2007-06-08 Thread half . italian
On Jun 8, 8:41 am, alf <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I wonder how to launch from python default Windows browser? In fact I
> have the same question for Linux.
>
> thx in advancve,
> --
> alf

For posterity... On a mac

[sean:~] sean% open http://www.google.com

~Sean

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


Re: Bytes/File Size Format Function

2007-06-12 Thread half . italian
On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote:
> Quick file size formatting for all those seekers out there...
>
> import math
>
> def filesizeformat(bytes, precision=2):
> """Returns a humanized string for a given amount of bytes"""
> bytes = int(bytes)
> if bytes is 0:
> return '0bytes'
> log = math.floor(math.log(bytes, 1024))
> return "%.*f%s" % (
> precision,
> bytes / math.pow(1024, log),
> ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb']
> [int(log)]
> )

Life is odd.  I just came to the group with the specific purpose of
asking this exact question.  Who are you? :)

Thanks!

~Sean

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


Re: Bytes/File Size Format Function

2007-06-13 Thread half . italian
On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote:
> Quick file size formatting for all those seekers out there...
>
> import math
>
> def filesizeformat(bytes, precision=2):
> """Returns a humanized string for a given amount of bytes"""
> bytes = int(bytes)
> if bytes is 0:
> return '0bytes'
> log = math.floor(math.log(bytes, 1024))
> return "%.*f%s" % (
> precision,
> bytes / math.pow(1024, log),
> ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb']
> [int(log)]
> )

Wait a sec...what if you send it a large amount of bytes? Say...
bigger than 2147483647.  You'll get an OverflowError.   I thought you
had my solution...

~Sean

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


Re: Bytes/File Size Format Function

2007-06-13 Thread half . italian
On Jun 13, 12:48 am, [EMAIL PROTECTED] wrote:
> On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote:
>
>
>
> > Quick file size formatting for all those seekers out there...
>
> > import math
>
> > def filesizeformat(bytes, precision=2):
> > """Returns a humanized string for a given amount of bytes"""
> > bytes = int(bytes)
> > if bytes is 0:
> > return '0bytes'
> > log = math.floor(math.log(bytes, 1024))
> > return "%.*f%s" % (
> > precision,
> > bytes / math.pow(1024, log),
> > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb']
> > [int(log)]
> > )
>
> Wait a sec...what if you send it a large amount of bytes? Say...
> bigger than 2147483647.  You'll get an OverflowError.   I thought you
> had my solution...
>
> ~Sean


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


Re: Bytes/File Size Format Function

2007-06-13 Thread half . italian
On Jun 13, 12:48 am, [EMAIL PROTECTED] wrote:
> On Jun 12, 8:47 pm, samuraisam <[EMAIL PROTECTED]> wrote:
>
>
>
> > Quick file size formatting for all those seekers out there...
>
> > import math
>
> > def filesizeformat(bytes, precision=2):
> > """Returns a humanized string for a given amount of bytes"""
> > bytes = int(bytes)
> > if bytes is 0:
> > return '0bytes'
> > log = math.floor(math.log(bytes, 1024))
> > return "%.*f%s" % (
> > precision,
> > bytes / math.pow(1024, log),
> > ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb']
> > [int(log)]
> > )
>
> Wait a sec...what if you send it a large amount of bytes? Say...
> bigger than 2147483647.  You'll get an OverflowError.   I thought you
> had my solution...
>
> ~Sean

I take it back.

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


Windows XMLRPC Service

2007-06-17 Thread half . italian
Hi,

I'm trying to serve up a simple XMLRPC server as a windows service.  I
got it to run properly, I'm just not sure how to stop it properly.
Most of the documentation/examples I found for this was from forums,
so I'd love some links to relevant info also.  Here's what I
have...taken from the cookbook with the xmlrpc server added:

import win32serviceutil
import win32service
import win32event

import SimpleXMLRPCServer

class MyClass(object):
def hello(self):
return "Hello World!"

class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "PythonXMLRPC"
_svc_display_name_ = "PythonXMLRPC"

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)

# quit the xmlrpc sever
self.server.quit()

# And set my event.
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
# Serve up the XMLRPC forever
self.server =
SimpleXMLRPCServer.SimpleXMLRPCServer(("10.0.1.6", 8000))
self.server.register_instance(MyClass())
self.server.serve_forever()

win32event.WaitForSingleObject(self.hWaitStop)


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

~Sean

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


Re: Windows XMLRPC Service

2007-06-18 Thread half . italian
On Jun 18, 2:16 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Mon, 18 Jun 2007 00:25:25 -0300, <[EMAIL PROTECTED]> escribió:
>
>
>
>
>
> > I'm trying to serve up a simple XMLRPC server as a windows service.  I
> > got it to run properly, I'm just not sure how to stop it properly.
> > Most of the documentation/examples I found for this was from forums,
> > so I'd love some links to relevant info also.  Here's what I
> > have...taken from the cookbook with the xmlrpc server added:
>
> > 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)
>
> > # quit the xmlrpc sever
> > self.server.quit()
>
> What is quit()? As the server may be processing a request I'd move any  
> finalization code below, after exiting the while loop.
>
>
>
> > # And set my event.
> > win32event.SetEvent(self.hWaitStop)
>
> > def SvcDoRun(self):
> > # Serve up the XMLRPC forever
> > self.server =
> > SimpleXMLRPCServer.SimpleXMLRPCServer(("10.0.1.6", 8000))
> > self.server.register_instance(MyClass())
> > self.server.serve_forever()
>
> > win32event.WaitForSingleObject(self.hWaitStop)
>
> The simplest solution is to replace serve_forever with a loop waiting on  
> hWaitStop:
>
>  while WaitForSingleObject(self.hWaitStop, 0)==WAIT_TIMEOUT:
>  self.server.handle_request()
>
> Set the socket timeout to a reasonable value (you'll have to wait that  
> time before exiting). Also, a ThreadingTCPServer may be better if you  
> expect more than a request at a time. If you search past messages you may  
> find other ways.
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -

I can't quite figure out where to set the "socket timeout".  I tried
setting win32event.WAIT_TIMEOUT, but I'm pretty sure that's not the
variable you were talking about.  I did manage to make it multi-
threaded by incorporating a different recipe, and I'm beginning to
understand the control flow a bit better, but it doesn't seem to be
doing what I expect.  When SvcStop() is executed and calls
win32event.SetEvent(self.hWaitStop), the while loop should break as
win32event.WaitForSingleObject(self.hWaitStop, 0) returns zero at this
point.  But it doesn't do that.  What am I missing?

import win32serviceutil
import win32service
import win32event

import SocketServer
from SimpleXMLRPCServer import
SimpleXMLRPCServer,SimpleXMLRPCRequestHandler

# Threaded mix-in
class
AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer):
pass


class MyClass(object):
def hello(self):
return "Hello World"

class SmallestPythonService(win32serviceutil.ServiceFramework):
_svc_name_ = "PythonXMLRPC"
_svc_display_name_ = "PythonXMLRPC"

def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
# Create an event which we will use to wait on.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
import socket
localhost = socket.gethostbyname(socket.gethostname())
self.server = AsyncXMLRPCServer((localhost, 8000),
SimpleXMLRPCRequestHandler)

def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
#print "EVENT:",
win32event.WaitForSingleObject(self.hWaitStop, 0) # returns 0 here

def SvcDoRun(self):
self.server.register_instance(MyClass())

#win32event.WAIT_TIMEOUT = 2 --- This just makes the loop
never execute because
# the WaitFor... part always returns 258

while win32event.WaitForSingleObject(self.hWaitStop, 0) ==
win32event.WAIT_TIMEOUT:
self.server.handle_request()

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

Thanks for any help!

~Sean

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

Re: Windows XMLRPC Service

2007-06-19 Thread half . italian
On Jun 19, 10:21 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 19 Jun 2007 03:45:19 -0300, <[EMAIL PROTECTED]> escribió:
>
> > I can't quite figure out where to set the "socket timeout".  I tried
> > setting win32event.WAIT_TIMEOUT, but I'm pretty sure that's not the
> > variable you were talking about.  I did manage to make it multi-
> > threaded by incorporating a different recipe, and I'm beginning to
> > understand the control flow a bit better, but it doesn't seem to be
> > doing what I expect.  When SvcStop() is executed and calls
> > win32event.SetEvent(self.hWaitStop), the while loop should break as
> > win32event.WaitForSingleObject(self.hWaitStop, 0) returns zero at this
> > point.  But it doesn't do that.  What am I missing?
>
> May be because you didn't set correctly the socket timeout. See the  
> comments below.
>
>
>
> > def SvcStop(self):
> > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
> > win32event.SetEvent(self.hWaitStop)
> > #print "EVENT:",
> > win32event.WaitForSingleObject(self.hWaitStop, 0) # returns 0 here
>
> That's OK, since you have set the event.
>
> > def SvcDoRun(self):
> > self.server.register_instance(MyClass())
>
> > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop
> > never execute because
> > # the WaitFor... part always returns 258
>
> WAIT_TIMEOUT is 258. How do you see it is 2?
> For example, see .
> Python 2.5.1 + pywin32 210 prints this on my PC:
> py> import win32event
> py> win32event.WAIT_TIMEOUT
> 258
>
> > while win32event.WaitForSingleObject(self.hWaitStop, 0) ==
> > win32event.WAIT_TIMEOUT:
> > self.server.handle_request()
>
> The loop above should keep running until hWaitStop is set, with a maximum  
> wait time (inside handle_request) corresponding to the socket timeout  
> value.
> You can either:
> - use socket.setdefaulttimeout() (in __init__, by example) before anything  
> else. This will set a global timeout for all sockets.
> - modify the socket instance. Just add this method to your AsyncServer:
>  def server_activate(self):
>  SimpleXMLRPCServer.server_activate(self)
> self.socket.settimeout(15) # for 15 secs
>
> --
> Gabriel Genellina

> > def SvcDoRun(self):
> > self.server.register_instance(MyClass())
>
> > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop
> > never execute because
> > # the WaitFor... part always returns 258
>
> WAIT_TIMEOUT is 258. How do you see it is 2?
> For example, see .
> Python 2.5.1 + pywin32 210 prints this on my PC:
> py> import win32event
> py> win32event.WAIT_TIMEOUT
> 258

I meant here that *if* I set the WAIT_TIMEOUT to 2, then I see that
behavior.

> - use socket.setdefaulttimeout() (in __init__, by example) before anything  
> else. This will set a global timeout for all sockets.

That was the one that did it.

Thank you again Gabriel.  I'll post back with something complete.

~Sean

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

Re: Windows XMLRPC Service

2007-06-20 Thread half . italian
On Jun 19, 12:32 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 19 Jun 2007 14:57:10 -0300, <[EMAIL PROTECTED]> escribió:
>
> >> > #win32event.WAIT_TIMEOUT = 2 --- This just makes the loop
> >> > never execute because
> >> > # the WaitFor... part always returns 258
>
> >> WAIT_TIMEOUT is 258. How do you see it is 2?
> >> py> import win32event
> >> py> win32event.WAIT_TIMEOUT
> >> 258
>
> > I meant here that *if* I set the WAIT_TIMEOUT to 2, then I see that
> > behavior.
>
> Ah, ok! I should have stated clearly that WAIT_TIMEOUT is a Windows  
> predefined constant, not your desired timeout value.
>
> > Thank you again Gabriel.  I'll post back with something complete.
>
> Yes, please, a working example would be nice for future readers...
>
> --
> Gabriel Genellina

For posterity...

import sys
import win32serviceutil
import win32service
import win32event
import win32evtlogutil
import servicemanager

import SocketServer, socket
from SimpleXMLRPCServer import
SimpleXMLRPCServer,SimpleXMLRPCRequestHandler

# Threaded mix-in
class
AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer):
pass

import XMLRPC_funcs # module containing the functions wrapped in a
class

class XMLRPCservice(win32serviceutil.ServiceFramework):
_svc_name_ = "PythonXMLRPC"
_svc_display_name_ = "PythonXMLRPC"
_svc_description_ = "Multi-threaded Python XMLRPC Server"

def __init__(self, args):
# set the timeout so the service can stop...Otherwise it hangs
forever
socket.setdefaulttimeout(15)

win32evtlogutil.AddSourceToRegistry(self._svc_display_name_,
sys.executable, "Application")
win32serviceutil.ServiceFramework.__init__(self, args)

# Create an event which we will use to wait on.
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
localhost = socket.gethostbyname(socket.gethostname())
self.server = AsyncXMLRPCServer((localhost, 8000),
SimpleXMLRPCRequestHandler)

def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#send the stop event
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
# log a start msg
 
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
  servicemanager.PYS_SERVICE_STARTED,
  (self._svc_name_, ' (%s)' %
self._svc_name_))

self.server.register_instance(XMLRPC_funcs.XMLRPC_funcs())

# handle requests until the stop event is received
while win32event.WaitForSingleObject(self.hWaitStop, 0) ==
win32event.WAIT_TIMEOUT:
self.server.handle_request()

# log a stopped msg
win32evtlogutil.ReportEvent(self._svc_name_,
servicemanager.PYS_SERVICE_STOPPED,
0,
 
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_,""))

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

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

Re: string formatter %x and a class instance with __int__ or __long__ cannot handle long

2007-06-20 Thread half . italian
On Jun 20, 8:24 pm, "Kenji Noguchi" <[EMAIL PROTECTED]> wrote:
> Hi
>
> I'm using Python 2.4.4 on 32bit x86 Linux.  I have a problem with printing
> hex string for a value larger than 0x8 when the value is given to
> % operator via an instance of a class with __int__().  If I pass a long value
> to % operator it works just fine.
>
> Example1 -- pass a long value directly.  this works.>>> x=0x8000
> >>> x
> 2147483648L
> >>> type(x)
> 
> >>> "%08x" % x
>
> '8000'
>
> Example2 -- pass an instance of a class with __int__()>>> class X:
>
> ... def __init__(self, v):
> ... self.v = v
> ... def __int__(self):
> ... return self.v
> ...>>> y = X(0x8000)
> >>> "%08x" % y
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: int argument required
>
>
>
> The behavior looks inconsistent.  By the way __int__ actually
> returned a long type value in the Example2.  The "%08x" allows
> either int or long in the Example1, however it accepts int only
> in the Example2.   Is this a bug or expected?
>
> by the way same thing happends on a 64bit system with a
> value of 0x8000.
>
> Regards,
> Kenji Noguchi

In your second example y is an instance of class X...not an int.  y.v
is an int.  Are you hoping it will cast it to an int as needed using
your method?  If so, I think you need to do so explicitly...ie "%08x"
% int(y)

~Sean

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


Re: Split file into several and reformat

2007-06-21 Thread half . italian
On Jun 20, 10:45 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I want to take read an input file (sels.txt) that looks like:
>
> Begin sels
>sel1 = {1001, 1002, 1003, ...
>...
>1099}
>
>sel2 = {1001, 1008, 1009 ...
>...
>1299}
> End sels
>
> And turn it into an output file for each of the "sels" in the input file, i.e
> sel1.txt:
>
> L1001
> L1002
> L1003
> ...
> L1099
>
> and sel2.txt:
>
> L1001
> L1008
> L1009
> ...
> L1299
>
> And so on. Many thanks,
> Wayne

hehe...

After Bruno's suggested read, go here: http://docs.python.org/tut/

Look at the string module.. specifically .strip() and .split(",")
Also look at reading files and perhaps lists.

for line in open("filename.txt", 'r').readlines():
handle_the_line()

Good Luck.

~Sean

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


Re: How to create a file with read access rights

2007-06-21 Thread half . italian
On Jun 21, 8:27 am, Johny <[EMAIL PROTECTED]> wrote:
> Is  it possible to  create a file on Linux  with access rights?
> For example
>  owner can read and write into the file
> others can only read from the file
> Thanks for replies
> L.

That all depends on your umask.  Most commonly, the default value is
022 which translates to 755 or ower has full control, and all others
can read and execute.  If you'd like to change a specific files
permissios with python, look into os.chmod()

~Sean

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


Re: regular expressions eliminating filenames of type foo.thumbnail.jpg

2007-06-24 Thread half . italian
On Jun 24, 10:00 pm, Justin Ezequiel <[EMAIL PROTECTED]>
wrote:
> Why not ditch regular expressions altogether for this problem?
>
> [ p for p in os.listdir(dir)
>   if os.path.isfile(os.path.join(dir,p))
>   and p.lower().find('.thumbnail.')==-1 ]

I like `and '.thumbnail.' not in p]` as a better ending. :)

~Sean

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


Re: can't start Apache on Mac OS X--no listening sockets available?

2007-06-25 Thread half . italian
On Jun 25, 7:23 pm, 7stud <[EMAIL PROTECTED]> wrote:
> I'm trying to get Apache set up on my system so I can use mod_python.
> I installed Apache 2.2.4 according to the following instructions:
>
> http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o...
>
> and everything seemed to install correctly, but I can't start Apache.
> I typed in the following command:
>
> $ sudo /Library/Apache2/bin/apachectl start
> Password:
>
> and I got this error message:
>
> httpd: Could not reliably determine the server's fully qualified
> domain name, using tms-computer.local for ServerName
> (48)Address already in use: make_sock: could not bind to address
> 0.0.0.0:80
> no listening sockets available, shutting down
> Unable to open logs
>
> Any ideas?

Do you have "Web Sharing" in the prefs on as well?  Possibly the built-
in apache is already started on port 80.

I've had luck with these: http://www.serverlogistics.com/downloads.php

Except it's tuff to compile new versions into these.  I failed at
getting PHP5 running under it, but they work well out of the box.

~Sean

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


Re: can't start Apache on Mac OS X--no listening sockets available?

2007-06-26 Thread half . italian
On Jun 25, 11:09 pm, 7stud <[EMAIL PROTECTED]> wrote:
> > On Jun 25, 7:23 pm, 7stud <[EMAIL PROTECTED]> wrote:
>
> > > I'm trying to get Apache set up on my system so I can use mod_python.
> > > I installed Apache 2.2.4 according to the following instructions:
>
> > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o...
>
> > > and everything seemed to install correctly, but I can't start Apache.
> > > I typed in the following command:
>
> > > $ sudo /Library/Apache2/bin/apachectl start
> > > Password:
>
> > > and I got this error message:
>
> > > httpd: Could not reliably determine the server's fully qualified
> > > domain name, using tms-computer.local for ServerName
> > > (48)Address already in use: make_sock: could not bind to address
> > > 0.0.0.0:80
> > > no listening sockets available, shutting down
> > > Unable to open logs
>
> > > Any ideas?
>
> > Do you have "Web Sharing" in the prefs on as well?  
>
> I checked and to my surprise Personal Web Sharing was turned on.  I
> was messing around with it yesterday because I thought that might have
> something to do with my problems, but I couldn't get Personal Web
> Sharing to start--it just said "Web Sharing starting up...", and it
> never did.
>
> Anyway, I turned Personal Web Sharing off, and then the error message
> changed to this:
>
> $ sudo /Library/Apache2/bin/apachectl start
> Password:
> httpd: Could not reliably determine the server's fully qualified
> domain name, using tms-computer.local for ServerName
>
> However, I checked the All Processes page in the Activity Monitor, and
> it said httpd was running.  So I tested my apache installation by
> typing http:/localhost in Safari's address bar, and a page displayed
> saying "It works!".  But I wondered if that page was being served up
> by the pre-installed version of Apache or my new installation.  So, I
> went into my new installation's directory and looked at the file:
>
> /Library/Apache2/htdocs/index.html
>
> and changed the text from "It works!" to "Apache 2.2.4", but when I
> retyped http:/localhost in Safari's address bar, I still got a page
> saying "It works!", so that page is not being served by my new
> installation.

Console and the system logs are an invaluable debugging tool on Macs.
Bet you have some errors there saying why apache couldnt stop/start.

Glad you got it working.

~Sean

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


Re: Tkinter: different results from the same tcl script

2007-06-26 Thread half . italian
On Jun 26, 1:06 am, Fabrizio Pollastri <[EMAIL PROTECTED]> wrote:
> Hello,
> in mixed python-tcl programming I found the following different
> behaviours of the same tcl script.
>
> If I type manually in the python interpreter the following lines
>
>  >>> from Tkinter import *
>  >>> w = Tk()
>  >>> w.tk.evalfile('my_tcl_script.tcl')
>
> where my_tcl_script.tcl is
>
> #!/bin/sh
> package require Tk
> wm withdraw .
> toplevel .root
> wm title .root "My title"
>
> I obtain one toplevel window with title "My title", as expected.
>
> The same result is obtained with the tcl shell command
>
> % wish my_tcl_script.tcl
>
> Now, I wish to run the same instructions from a python script. So, I
> written the following script
>
> from time import *
> from Tkinter import *
> w = Tk()
> w.tk.evalfile('my_tcl_script.tcl')
> sleep(3)
>
> I expected to see the same toplevel window for 3 seconds, but the result
> of this python script is nothing, no window appears.
>
> If anybody can explain the different behaviour and how to normalize it
> with the correct one, I will be very glad. Thank you in advance.
>
> F. Pollastri

You need a call to `w.mainloop()`

w=Tk()
w.after(3000, lambda: w.quit())
w.mainloop()

~Sean

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


Re: Getting importError: No module named _md5

2007-06-27 Thread half . italian
On Jun 27, 7:04 am, jeffself <[EMAIL PROTECTED]> wrote:
> I'm running Python 2.5.1 which I'm getting from the MacPort package
> system.  I just installed Django and tried to start up the Django
> server and I got the following error:
>
> ImportError: No module named _md5
>
> I'm pretty sure this is a python problem, not Django problem. I'm
> looking in the python2.5 directory and I see md5.py, md5.pyc and
> md5.pyo files.
>
> Any suggestions?

Try to load the md5 module from the interactive prompt.  Are you using
the python version you expect?  Try starting up your previous version
of python and see if you get the same error.  Delete the MacPort
install and install from source.

My 2 cents.

~Sean

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


Re: allow scripts to use .pth files?

2007-07-03 Thread half . italian
On Jul 3, 7:35 am, Alan Isaac <[EMAIL PROTECTED]> wrote:
> Suppose I have a directory `scripts`.
> I'd like the scripts to have access to a package
> that is not "installed", i.e., it is not on sys.path.
> On this list, various people have described a variety
> of tricks they use, but nobody has proposed a
> pretty way to allow this.
> I am therefore assuming there is not one. (?)
>
> How about allowing a `scripts.pth` file in such a `scripts`
> directory, to work like a path configuration file?
> (But to be used only when __name__=="__main__".)
> Drawbacks?
>
> Alan Isaac

import sys
sys.path.append("../scripts")

import Module_from_scripts_dir

~Sean

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread half . italian
On Jul 8, 5:06 pm, [EMAIL PROTECTED] wrote:
> i hope someone here can help me.
>
> basically, me and my friend have a summer project.
>
> in this project, we need something that would basically function as a
> blender. we know we'll need to buy a motor that spins, but what we're
> having trouble with is figuring out how to program it. we want to be
> able to control the speed of the motor. how would we accomplish this?
>
> i'm new to all of this, so i'm having a hard time wrapping my mind
> around how it'd be possible to program one of those things :\
>
> ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> turn the other direction.
>
> would you program it the same way you would on a personal computer
> (via c, python, etc)?

This might be interesting to you.

http://www.makingthings.com/

~Sean

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


Re: How to Machine A python script execute Machine B python script?

2007-07-08 Thread half . italian
On Jul 8, 6:45 pm, johnny <[EMAIL PROTECTED]> wrote:
> Anyone know how I can make Machine A python script execute a python
> script on Machine B ?

xmlrpc will work.

~Sean

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


Re: image sequence to Quicktime movie

2007-04-18 Thread half . italian
I haven't experimented with it myself, but you'll probably find what
you need here. (Only works on original mac python distribution)

[sean:~] sean% python
Python 2.3.5 (#1, Aug 12 2006, 00:08:11)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from Carbon import Qt
>>> dir(Qt)
['AddSoundDescriptionExtension', 'AddTime', 'AlignWindow',
'CanQuickTimeOpenDataRef', 'CanQuickTimeOpenFile',
'ClearMoviesStickyError', 'CloseMovieFile', 'ConvertTime',
'ConvertTimeScale', 'CreateMovieFile', 'CreateShortcutMovieFile',
'DeleteMovieFile', 'DisposeMatte', 'DragAlignedWindow',
'EndFullScreen', 'EnterMovies', 'Error', 'ExitMovies',
'FlashMediaDoButtonActions', 'FlashMediaFrameLabelToMovieTime',
'FlashMediaFrameNumberToMovieTime',
'FlashMediaGetDisplayedFrameNumber', 'FlashMediaGetFlashVariable',
'FlashMediaGetRefConBounds', 'FlashMediaGetRefConID',
'FlashMediaGetSupportedSwfVersion', 'FlashMediaIDToRefCon',
'FlashMediaSetFlashVariable', 'FlashMediaSetPan', 'FlashMediaSetZoom',
'FlashMediaSetZoomRect', 'GetDataHandler',
'GetMovieImporterForDataRef', 'GetMoviesError',
'GetMoviesStickyError', 'GetSoundDescriptionExtension', 'Media',
'Media3DGetCameraAngleAspect', 'Media3DGetCameraData',
'Media3DGetCameraRange', 'Media3DGetCurrentGroup',
'Media3DRotateNamedObjectTo', 'Media3DScaleNamedObjectTo',
'Media3DSetCameraAngleAspect', 'Media3DSetCameraData',
'Media3DSetCameraRange', 'Media3DTranslateNamedObjectTo', 'MediaType',
'Movie', 'MovieController', 'MovieControllerType', 'MovieType',
'MoviesTask', 'MusicMediaGetIndexedTunePlayer', 'NewMovie',
'NewMovieFromDataFork', 'NewMovieFromDataFork64',
'NewMovieFromDataRef', 'NewMovieFromFile', 'NewMovieFromHandle',
'NewMovieFromScrap', 'NewTimeBase', 'NewUserData',
'NewUserDataFromHandle', 'OpenMovieFile', 'PasteHandleIntoMovie',
'QTDismissStandardParameterDialog', 'QTGetMIMETypeInfo',
'QTIsStandardParameterDialogEvent', 'QTNewAlias',
'QTRegisterAccessKey', 'QTStandardParameterDialogDoAction',
'QTTextToNativeText', 'QTUnregisterAccessKey', 'RemoveMovieResource',
'RemoveSoundDescriptionExtension', 'SpriteMediaCountImages',
'SpriteMediaCountSprites', 'SpriteMediaDisposeSprite',
'SpriteMediaGetActionVariable',
'SpriteMediaGetActionVariableAsString',
'SpriteMediaGetDisplayedSampleNumber', 'SpriteMediaGetImageName',
'SpriteMediaGetIndImageDescription', 'SpriteMediaGetProperty',
'SpriteMediaGetSpriteName', 'SpriteMediaGetSpriteProperty',
'SpriteMediaHitTestAllSprites', 'SpriteMediaHitTestOneSprite',
'SpriteMediaHitTestSprites', 'SpriteMediaSetActionVariable',
'SpriteMediaSetActionVariableToString', 'SpriteMediaSetProperty',
'SpriteMediaSetSpriteProperty', 'SpriteMediaSpriteIDToIndex',
'SpriteMediaSpriteIndexToID', 'SubtractTime',
'TextMediaAddHiliteSample', 'TextMediaAddTESample',
'TextMediaAddTextSample', 'TextMediaDrawRaw', 'TextMediaFindNextText',
'TextMediaGetTextProperty', 'TextMediaHiliteTextSample',
'TextMediaRawIdle', 'TextMediaRawSetup', 'TextMediaSetTextProperty',
'TextMediaSetTextSampleData', 'TimeBase', 'TimeBaseType', 'Track',
'TrackTimeToMediaTime', 'TrackType', 'UserData', 'UserDataType',
'VideoMediaGetCodecParameter', 'VideoMediaGetStallCount',
'VideoMediaGetStatistics', 'VideoMediaResetStatistics',
'VideoMediaSetCodecParameter', '__builtins__', '__doc__', '__file__',
'__name__']
>>>

~Sean

On Apr 18, 10:16 am, Simon Cassels <[EMAIL PROTECTED]> wrote:
> did u ever find anything out about this ?
>
> if so can you help me with some leads i am trying to figure an action  
> that can convert image files to quicktime automatically.
>
> cheers
> simon


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


Re: About installing new Python version.

2007-04-19 Thread half . italian
On Apr 19, 2:03 am, king kikapu <[EMAIL PROTECTED]> wrote:
> Hi to all,
>
> i started with Python at v2.5 and now i see that a new version is
> released.
> As i already have a lot of stuff for Python installed in the site-
> packages directory, which is the correct way to install a new Python
> version without do any damage ?
>
> Remove Python and ALL Python related software and install them all
> over again (painful)?
> Remove Python and do not touch anything else and install new version
> on top of them at the same directory ?
> Any other choice available ?
>
> Thanks a lot for any help!

Just install the new version. It should link everything back up so the
new version is active, but the old versions are intact.

~Sean

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


Re: NFS Help

2007-04-19 Thread half . italian
On Apr 19, 11:32 am, Clement <[EMAIL PROTECTED]> wrote:
> how to get the file from NFS share in python..

You need to be more specific.

If you just want to copy a file try shutil

http://docs.python.org/lib/module-shutil.html

~Sean

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


Re: recursion depth problem

2007-04-22 Thread half . italian
On Apr 22, 11:49 am, proctor <[EMAIL PROTECTED]> wrote:
> hello,
>
> i have a small function which mimics binary counting.  it runs fine as
> long as the input is not too long, but if i give it input longer than
> 8 characters it gives
>
> RuntimeError: maximum recursion depth exceeded in cmp
>
> i'm not too sure what i am doing improperly.  is there really a lot of
> recursion in this code?
>
> ==
>
> import sys
>
> def ch4(item, n=0):
> if n < len(item):
> if item[n] == '0':
> item[n] = '1'
> print ''.join(item)
> ch4(item)
> elif item[n] == '1':
> item[n] = '0'
> ch4(item, n+1)
>
> ch4(list(sys.argv[1]))
>
> ==
>
> this function expects input in the form of a string of zeros, like
> this:
>
> python test-bin.py 
>
> and is expected to output a list of permutations like this:
>
> $ python test-bin.py 
> 1000
> 0100
> 1100
> 0010
> 1010
> 0110
> 1110
> 0001
> 1001
> 0101
> 1101
> 0011
> 1011
> 0111
> 
>
> thanks for all help!
>
> sincerely,
> proctor

If you just want to make it work as ischeck

sys.setrecursionlimit()

~Sean

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


Re: Redirection problem

2007-04-23 Thread half . italian
On Apr 23, 9:10 am, CSUIDL PROGRAMMEr <[EMAIL PROTECTED]> wrote:
> I am new to python. so be patient with me
>
> I am trying to redirect the output of os.popen command to a file. I
> want to append to that file. but instead of appending. The file only
> shows last command that was writtenn to  it.
>
>  filehandle= open("/root/yhpc-2.0/installer/yhpc-log" ,"a+");
> filehandle.write(" Command executed is " + cmd);
> try:
>   pipe= os.popen('%s > /root/yhpc-2.0/installer/yhpc-log' %cmd );
> except : IOError;
>   filehandle.close();
>
> Any  suggestion would help.
>
> filehandle.close();

This works.

f = open("test", 'a')
stdout = os.popen("ls -l /")
f.write(stdout.read())
f.close()

~Sean

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


Re: Generate report containing pdf or ps figures?

2007-04-23 Thread half . italian
On Apr 23, 9:30 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> I need to be able to generate a PDF report which consists
> mostly of vector images (which I can generate as encapsulated
> Postscript, PDF, or SVG).  What I need is a way to combine
> these figures into a single PDF document.  Right now the
> reports consist entire of these figures, so I just write the
> figures out to temp files and then use os.system() to run
> ghostscript with appropriate options to combine them into a
> single PDF file.
>
> I'd like to be able to add some text and/or place the figures
> in a manner other than one per page in the output document.
>
> I've looked at ReportLab's documentation, but although it
> appears to be able to use bitmap images (e.g jpeg) it doesn't
> appear to be able to use vector images (EPS/PDF/SVG).
>
> Is there a PDF generation library that can place EPS or
> PDF figures on a page?
>
> --
> Grant Edwards   grante Yow! Is a tattoo real, like
>   at   a curb or a battleship?
>visi.comOr are we suffering in
>Safeway?

On a Mac...

http://developer.apple.com/graphicsimaging/pythonandquartz.html

~Sean

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


Re: Python Widget to read in user input box in blog

2007-04-23 Thread half . italian
On Apr 23, 6:57 pm, [EMAIL PROTECTED] wrote:
> Hey,
>
> I am helping to develop a project that displays images based on user
> input.  One possible way of implementing this is via a widget that
> when it is run, would read in the users input from an input text field
> (probably from a blog), and replace it with the HTML that would
> display those images.  This is more a proof of concept, so really all
> I am wondering is if there is a good way in Python to read in the text
> the user has typed and change it before the user hits submit?
>
> Thanks

Here's another way.  Although I'm not really sure whether you are
talking about a web app or a local gui app.

#! /usr/bin/env python

from Tkinter import *

class Window(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
Label(self, text="Enter the path to a gif").pack(padx=5, pady=5)
self.label = Label(self, text="")
self.label.pack(padx=5, pady=5)
self.entry = Entry(self, text="")
self.entry.pack(padx=5, pady=5)

self.pack()
self.update()

def update(self):
try:
self.image = PhotoImage(file=self.entry.get())
self.label.config(image=self.image)
except TclError:
self.label.config(text=self.entry.get(), image="")
self.after(20, self.update)

if __name__ == '__main__':
root = Tk()
Window().mainloop()

~Sean

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


Re: I can't inherit from "compiled" classes ?

2007-04-29 Thread half . italian
On Apr 29, 12:48 pm, "Maxim Veksler" <[EMAIL PROTECTED]> wrote:
> Hello list,
>
> I'm trying to subclass socket and select, for both I get:
> """ TypeError: Error when calling the metaclass bases
> module.__init__() takes at most 2 arguments (3 given) """, I don't
> understand this error. Why would python try to pass 3 arguments (what
> are they) ?
>
> Googling for this error gave random results talking about try to
> inherit a "Package" but socket is definitely a class,
> (/usr/lib/python2.4/socket.py). Not sure about select thought.
>
> I've did the following to receive the error:
> """
> In [1]: import socket
>
> In [2]: class PollingSocket(socket):
>...: pass
>...:
> ---
> exceptions.TypeError Traceback (most
> recent call last)
>
> /home/hq4ever/
>
> TypeError: Error when calling the metaclass bases
> module.__init__() takes at most 2 arguments (3 given)
> """
>
> What am I breaking wrong?
>
> Thank you,
> Maxim.
>
> --
> Cheers,
> Maxim Veksler
>
> "Free as in Freedom" - Do u GNU ?

Try:

import socket

class PollingSocket(socket.socket):
pass

~Sean

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


Re: os.path.join

2007-05-01 Thread half . italian
On May 1, 9:23 pm, Elliot Peele <[EMAIL PROTECTED]> wrote:
> On Tue, 2007-05-01 at 19:27 -0700, 7stud wrote:
> > On May 1, 7:36 pm, Elliot Peele <[EMAIL PROTECTED]> wrote:
> > > Why does os.path.join('/foo', '/bar') return '/bar' rather than
> > > '/foo/bar'? That just seems rather counter intuitive.
>
> > > Elliot
>
> > join(  path1[, path2[, ...]])
> > Join one or more path components intelligently. If any component is an
> > absolute path, all previous components (on Windows, including the
> > previous drive letter, if there was one) are thrown away...
>
> Yes, but that still doesn't answer my question as to why os.path.join
> works that way. I understand that that is how it is written, but why?
>
> Elliot

It makes perfect sense. You are joining two paths that both begin at
the root directory.  The second path is overwriting the first because
they can't both begin at the root and also be parts of one path.

A better question is why this doesn't work.

>>> pathparts = ["/foo", "bar"]
>>> os.path.join(pathparts)
['/foo', 'bar']

This should return a string in my opinion.

~Sean

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


Re: ScrolledText?

2007-05-01 Thread half . italian
On May 1, 3:12 pm, nik <[EMAIL PROTECTED]> wrote:
> I've been trying to get the scrollbar and text box always going to the
> last line and have been completely unsuccessful.
>
> I've tried, ScrolledText, text.see, and text.yview_pickplace without
> success
>
> for instance this was the last setup:
>
>  self.text = ScrolledText(master, relief=RIDGE)
>  self.text.grid(column=1, row=2, columnspan=10,\
> rowspan=5, pady=10, sticky=NSEW)
>
> with this text entry:
>
>  self.text.insert(END, ins)
>  self.text.yview_pickplace("end")
>
> Can anybody please tell me what I might be doing wrong, or an example
> that works, so that I can see what's going wrong.
>
> Thanks,
> Nik

try...

self.text.yview_moveto(1)

~Sean

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


Re: os.path.join

2007-05-02 Thread half . italian
On May 1, 11:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 02 May 2007 02:31:43 -0300, <[EMAIL PROTECTED]> escribió:
>
> > A better question is why this doesn't work.
>
>  pathparts = ["/foo", "bar"]
>  os.path.join(pathparts)
> > ['/foo', 'bar']
>
> > This should return a string in my opinion.
>
> I think it's a bug, but because it should raise TypeError instead.
> The right usage is os.path.join(*pathparts)
>
> --
> Gabriel Genellina

Wow.  What exactly is that * operator doing?  Is it only used in
passing args to functions?  Does it just expand the list into
individual string arguments for exactly this situation?  Or does it
have other uses?

~Sean

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


Re: os.path.join

2007-05-02 Thread half . italian
On May 2, 12:36 am, Ant <[EMAIL PROTECTED]> wrote:
> On May 2, 8:03 am, [EMAIL PROTECTED] wrote:
>
> > On May 1, 11:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> ...
> > > I think it's a bug, but because it should raise TypeError instead.
> > > The right usage is os.path.join(*pathparts)
> ...
> > Wow.  What exactly is that * operator doing?  Is it only used in
> > passing args to functions?  Does it just expand the list into
> > individual string arguments for exactly this situation?  Or does it
> > have other uses?
>
> It's used for unpacking a collection into arguments to a function.
> It's also used at the other end for receiving a variable length set of
> arguments. i.e.
>
> >>> x = (1,3)
> >>> def add(a, b):
>
> return a + b
>
> >>> add(*x)
> 4
> >>> def add(*args):
>
> return reduce(int.__add__, args)
>
> >>> add(1,2,3,4,5,6)
> 21
> >>> add(*x)
>
> 4
>
> The same sort of thing holds for keyword arguments:
>
> >>> def print_kw(**kw):
>
>  for k in kw:
>  print kw[k]
>
> >>> print_kw(a=1, b=2)
>
> 1
> 2>>> d = {'a': 1, 'b': 10, 'c': 100}
> >>> print_kw(**d)
>
> 1
> 100
> 10

Thank you both.

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


Re: progress

2007-05-05 Thread half . italian
On May 5, 1:46 am, Merrigan <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I have posted yesterday about an ftplib issue, this has been resolved.
>
> I actually want to ask something here...
>
> The script that that ftplib error was from...I was wondering - What do
> I need to do to print the stats (speed/s, percentage done) of the
> upload that is running on the monitor.
>
> This script runs on a Fedora Machine.
>
> Thanx for the help guys!
>
>  -- Merrigan

Looks like all you've got on the Python side is the size() method.
You could start a timer when the transfer begins, and then compare the
size on the server versus the size locally to get progress.

~Sean

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


Re: long lists

2007-05-07 Thread half . italian
On May 7, 5:14 am, Merrigan <[EMAIL PROTECTED]> wrote:
> On May 7, 10:18 am, Steven D'Aprano
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Mon, 07 May 2007 00:28:14 -0700, Merrigan wrote:
> > > 1. I have the script popping all the files that need to be checked into
> > > a list, and have it parsing the list for everything...Now the problem is
> > > this : The sever needs to check (at the moment) 375 files and eliminate
> > > those that don't need reuploading. This number will obviously get bigger
> > > and bigger as more files gets uploaded. Now, the problem that I'm having
> > > is that the script is taking forever to parse the list and give the
> > > final result. How can I speed this up?
>
> > By writing faster code???
>
> > It's really hard to answer this without more information. In particular:
>
> > - what's the format of the list and how do you parse it?
>
> > - how does the script decide what files need uploading?
>
> > --
> > Steven.
>
> Hi, Thanx for the reply,
>
> The Script it available at this url 
> :http://www.lewendewoord.co.za/theScript.py
>
> P.S. I know it looks like crap, but I'm a n00b, and not yet through
> the OOP part of the tutorial.
>
> Thanx in advance!

Do you have access to the machine via ssh?  I would try to get away
from FTP and use rsync for this kind of thing if possible.

~Sean

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


Re: Checking if string inside quotes?

2007-05-09 Thread half . italian
On May 9, 1:39 pm, "Michael Yanowitz" <[EMAIL PROTECTED]> wrote:
> Hello:
>
>If I have a long string (such as a Python file).
> I search for a sub-string in that string and find it.
> Is there a way to determine if that found sub-string is
> inside single-quotes or double-quotes or not inside any quotes?
> If so how?
>
> Thanks in advance:
> Michael Yanowitz

I think the .find() method returns the index of the found string.  You
could check one char before and then one char after the length of the
string to see.  I don't use regular expressions much, but I'm sure
that's a more elegant approach.

This will work. You'll get in index error if you find the string at
the very end of the file.

s = """
foo
"bar"
"""
findme = "foo"
index = s.find(findme)

if s[index-1] == "'" and s[index+len(findme)] == "'":
print "single quoted"
elif s[index-1] == "\"" and s[index+len(findme)] == "\"":
   print "double quoted"
else:
   print "unquoted"

~Sean

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


Re: File I/O

2007-05-09 Thread half . italian
On May 9, 2:13 pm, HMS Surprise <[EMAIL PROTECTED]> wrote:
> If one has a list of lists such as
>
> lst = [['a','1'],['b','2']]
>
> is there a standard python idiom for writing and reading the pairs to/
> from a file?
>
> Thanks,
>
> jh

These work.  Assuming you can choose the format.  Or you could pickle
the list.

write

lst = [['a','1'],['b','2']]

file = open("file", 'w')
[file.write(item[0] + "\t" + item[1] + "\n") for item in lst]
file.close()

read

lst = []
file = open("file", 'r')
[lst.append(list(line.split())) for line in file]
file.close()

print lst

~Sean

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


Re: Checking if string inside quotes?

2007-05-09 Thread half . italian
On May 9, 2:31 pm, "Michael Yanowitz" <[EMAIL PROTECTED]> wrote:
> Thanks, but it is a little more complicated than that,
>   the string could be deep in quotes.
>
>The problem is in string substitution.
> Suppose I have a dictionary with MY_IP : "172.18.51.33"
>
>   I need to replace all instances of MY_IP with "172.18.51.33"
> in the file.
>   It is easy in cases such as:
>   if (MY_IP == "127.0.0.1"):
>
>   But suppose I encounter:"
>  ("(size==23) and (MY_IP==127.0.0.1)")
>
>In this case I do not want:
>  ("(size==23) and ("172.18.51.33"==127.0.0.1)")
> but:
>  ("(size==23) and (172.18.51.33==127.0.0.1)")
> without the internal quotes.
>  How can I do this?
>   I presumed that I would have to check to see if the string
> was already in quotes and if so remove the quotes. But not
> sure how to do that?
>   Or is there an easier way?
>
> Thanks in advance:
> Michael Yanowitz
>
> -Original Message-
> From: [EMAIL PROTECTED]
>
> [mailto:[EMAIL PROTECTED] Behalf
> Of [EMAIL PROTECTED]
> Sent: Wednesday, May 09, 2007 5:12 PM
> To: [EMAIL PROTECTED]
> Subject: Re: Checking if string inside quotes?
>
> On May 9, 1:39 pm, "Michael Yanowitz" <[EMAIL PROTECTED]> wrote:
> > Hello:
>
> >If I have a long string (such as a Python file).
> > I search for a sub-string in that string and find it.
> > Is there a way to determine if that found sub-string is
> > inside single-quotes or double-quotes or not inside any quotes?
> > If so how?
>
> > Thanks in advance:
> > Michael Yanowitz
>
> I think the .find() method returns the index of the found string.  You
> could check one char before and then one char after the length of the
> string to see.  I don't use regular expressions much, but I'm sure
> that's a more elegant approach.
>
> This will work. You'll get in index error if you find the string at
> the very end of the file.
>
> s = """
> foo
> "bar"
> """
> findme = "foo"
> index = s.find(findme)
>
> if s[index-1] == "'" and s[index+len(findme)] == "'":
> print "single quoted"
> elif s[index-1] == "\"" and s[index+len(findme)] == "\"":
>print "double quoted"
> else:
>print "unquoted"
>
> ~Sean
>
> --http://mail.python.org/mailman/listinfo/python-list

In that case I suppose you'd have to read the file line by line and if
you find your string in the line then search for the indexes of any
matching quotes.  If you find matching quotes, see if your word lies
within any of the quote indexes.

#!/usr/bin/env python

file = open("file", 'r')
findme= "foo"
for j, line in enumerate(file):
found = line.find(findme)
if found != -1:
quotecount = line.count("'")
quoteindexes = []
start = 0
for i in xrange(quotecount):
i = line.find("'", start)
quoteindexes.append(i)
start = i+1

f = False
for i in xrange(len(quoteindexes)/2):
if findme in
line[quoteindexes.pop(0):quoteindexes.pop(0)]:
f = True
print "Found %s on line %s: Single-Quoted" % (findme, j
+1)
if not f:
print "Found %s on line %s: Not quoted" % (findme, j+1)


It's not pretty but it works.

~Sean

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


Re: replacing string in xml file--revisited

2007-05-10 Thread half . italian
On May 10, 12:56 am, [EMAIL PROTECTED] wrote:
> Hi,
>  I need to replace a string in xml file with something else.Ex
>
> - 
>   rate
>   rate
>   
>   
>   
> - 
>
>  Here i have opened an xml
> file(small part is pasted here).I want to replace the word 'localId'
> with 'dataPackageID' wherever it comes in xml file.I have asked this
> before and got a code:
> input_file = open(filename)
> xmlcontents = input_file.read()
> input_file.close()
> xmlcontents = xmlcontents.replace("spam", "eggs")
> output_file = open(filename,"w")
> output_file.write(xmlcontents)
> output_file.close()
>
>  Although this works alone it is nto
> working when i handle multiple file I/O.Is there a alternative to do
> this.(maybe without read() operation)
>  Thanks

try this...

#!/usr/bin/env python

from elementtree import ElementTree as et
tree = et.parse("testxml.xml")

for t in tree.getiterator("SERVICEPARAMETER"):
t.set("Semantics", "localId")

tree.write("output.xml")

~Sean

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


Re: replacing string in xml file--revisited

2007-05-10 Thread half . italian
On May 10, 12:56 am, [EMAIL PROTECTED] wrote:
> Hi,
>  I need to replace a string in xml file with something else.Ex
>
> - 
>   rate
>   rate
>   
>   
>   
> - 
>
>  Here i have opened an xml
> file(small part is pasted here).I want to replace the word 'localId'
> with 'dataPackageID' wherever it comes in xml file.I have asked this
> before and got a code:
> input_file = open(filename)
> xmlcontents = input_file.read()
> input_file.close()
> xmlcontents = xmlcontents.replace("spam", "eggs")
> output_file = open(filename,"w")
> output_file.write(xmlcontents)
> output_file.close()
>
>  Although this works alone it is nto
> working when i handle multiple file I/O.Is there a alternative to do
> this.(maybe without read() operation)
>  Thanks

After reading your post again, this might be better:

#!/usr/bin/env python

from elementtree import ElementTree as et
tree = et.parse("testxml.xml")

for t in tree.getiterator("SERVICEPARAMETER"):
if t.get("Semantics") == "localId":
t.set("Semantics", "dataPackageID")

tree.write("output.xml")

~Sean

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


Re: replacing string in xml file--revisited

2007-05-10 Thread half . italian
On May 10, 4:21 am, [EMAIL PROTECTED] wrote:
> On May 10, 1:55 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On May 10, 12:56 am, [EMAIL PROTECTED] wrote:
>
> > > Hi,
> > >  I need to replace a string in xml file with something else.Ex
>
> > > - 
> > >   rate
> > >   rate
> > >   
> > >   
> > >   
> > > - 
>
> > >  Here i have opened an xml
> > > file(small part is pasted here).I want to replace the word 'localId'
> > > with 'dataPackageID' wherever it comes in xml file.I have asked this
> > > before and got a code:
> > > input_file = open(filename)
> > > xmlcontents = input_file.read()
> > > input_file.close()
> > > xmlcontents = xmlcontents.replace("spam", "eggs")
> > > output_file = open(filename,"w")
> > > output_file.write(xmlcontents)
> > > output_file.close()
>
> > >  Although this works alone it is nto
> > > working when i handle multiple file I/O.Is there a alternative to do
> > > this.(maybe without read() operation)
> > >  Thanks
>
> > After reading your post again, this might be better:
>
> > #!/usr/bin/env python
>
> > from elementtree import ElementTree as et
> > tree = et.parse("testxml.xml")
>
> > for t in tree.getiterator("SERVICEPARAMETER"):
> > if t.get("Semantics") == "localId":
> > t.set("Semantics", "dataPackageID")
>
> > tree.write("output.xml")
>
> > ~Sean- Hide quoted text -
>
> > - Show quoted text -
>
>  which module should be imported for above to work,it says
>  ImportError: No module named elementtree
>  Thanks

You can either 1) upgrade to python 2.5 which includes the elementtree
module or 2) download and add the module to your current installation

http://effbot.org/zone/element-index.htm

~Sean

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


Re: Newbie look at Python and OO

2007-05-10 Thread half . italian

walterbyrd wrote:
> I learned to program with Pascal, way back when. Went into software
> development for a while, then went into systems admin. Have programmed
> in several languages, just learning Python.
>
> Some things I find odd:
>
> 1) 5/-2 == -3?
>
> 2) list assignment handling, pointing two vars to the same list:
>
> With simple data types:
> >>> a = 5
> >>> b = a
> >>> a = 3
> >>> a,b
> (3, 5)
>
> Which is what I'd expect, since I have changed a, but not b.
>
> But with lists:
> >>> a = list("1234")
> >>> b = a
> >>> a.append("5")
> >>> a,b
> (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5'])
>
> b  changes even though I have not touched b. I know why, but this is
> not what I would ordinarilly expect, it does not seem intuitive. And,
> IMO, it gets worse:
>
> >>> a = list("1234")
> >>> b = a
> >>> a = a + ['5']
> >>> a,b
> (['1', '2', '3', '4', '5'], ['1', '2', '3', '4'])
>
> Sometimes changing a changes b, and sometimes not. You also have to
> remember that subseqent changes to a will not change b - after some
> operation but not others. To those who think in Python, I'm sure this
> all seems normal. But, having programmed in about one dozen other
> language, this seems downright bizare to me. I know why it works like
> this, but it seems like an odd way to do things.
>
> 3) ambiguous use of the form: this.that()
>
> Sometimes, this.that() means module.funcion() as in:
>
> >>> os.dirlist(".")
>
> Other times, "this" is sort of like a parameter to the "that"
> function:
>
> >>> a = list("1234")
> >>> "_".join(a)
> '1_2_3_4_5'
>
> And still other times, is seems that "this" is an object, acted upon
> by "that" :
>
> >>> a = list("1234")
> >>> b = "_".join(a)
> >>> b.split("_")
> ['1', '2', '3', '4', '5']
>
> BTW: it seems a bit odd to that the positions of the string, and the
> delimitor, are reversed between the complementory functions join(),
> and split(). I suppose if it weren't for OO, we have something
> terribly complicated, like:
>
> split(str, "_")
> join(str, "_")
>
> Again, those who think in Python, will understand right away that:
>
> math.count(x)
>
> is counting the substring "x" in the "math" string. But can you see
> where that might be confused to be a function called count() in the
> math module?
>
> I'm not complaining. Python is a great language in many respects. But,
> I would take some issue with those claiming Python is intuitive and
> easy. IMO: there seems to be many ambiguous, unintuitve, and
> confusing, aspects to Python.

These conversations are funny to me.  I use Python every day and I
have never actually thought about the implications of binding objects
to names, or two names pointing to the same object.  Problems of this
sort just never come up in actual programming for me.  It just works.

Python was my virgin language, so maybe that just makes it natural to
me, but it seems like people coming from other languages get hung up
on testing out the differences and theories rather than just
programming in it.  Alas, maybe I have yet to get deep enough to run
into these kinds of problems.

The question of what math is in math.count(x) makes sense, but this
one never comes up either (or rarely).  I usually know what the object
is that I'm working with.

~Sean

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


Re: Newbie look at Python and OO

2007-05-10 Thread half . italian
On May 10, 2:21 pm, [EMAIL PROTECTED] wrote:
> walterbyrd wrote:
> > I learned to program with Pascal, way back when. Went into software
> > development for a while, then went into systems admin. Have programmed
> > in several languages, just learning Python.
>
> > Some things I find odd:
>
> > 1) 5/-2 == -3?
>
> > 2) list assignment handling, pointing two vars to the same list:
>
> > With simple data types:
> > >>> a = 5
> > >>> b = a
> > >>> a = 3
> > >>> a,b
> > (3, 5)
>
> > Which is what I'd expect, since I have changed a, but not b.
>
> > But with lists:
> > >>> a = list("1234")
> > >>> b = a
> > >>> a.append("5")
> > >>> a,b
> > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5'])
>
> > b  changes even though I have not touched b. I know why, but this is
> > not what I would ordinarilly expect, it does not seem intuitive. And,
> > IMO, it gets worse:
>
> > >>> a = list("1234")
> > >>> b = a
> > >>> a = a + ['5']
> > >>> a,b
> > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4'])
>
> > Sometimes changing a changes b, and sometimes not. You also have to
> > remember that subseqent changes to a will not change b - after some
> > operation but not others. To those who think in Python, I'm sure this
> > all seems normal. But, having programmed in about one dozen other
> > language, this seems downright bizare to me. I know why it works like
> > this, but it seems like an odd way to do things.
>
> > 3) ambiguous use of the form: this.that()
>
> > Sometimes, this.that() means module.funcion() as in:
>
> > >>> os.dirlist(".")
>
> > Other times, "this" is sort of like a parameter to the "that"
> > function:
>
> > >>> a = list("1234")
> > >>> "_".join(a)
> > '1_2_3_4_5'
>
> > And still other times, is seems that "this" is an object, acted upon
> > by "that" :
>
> > >>> a = list("1234")
> > >>> b = "_".join(a)
> > >>> b.split("_")
> > ['1', '2', '3', '4', '5']
>
> > BTW: it seems a bit odd to that the positions of the string, and the
> > delimitor, are reversed between the complementory functions join(),
> > and split(). I suppose if it weren't for OO, we have something
> > terribly complicated, like:
>
> > split(str, "_")
> > join(str, "_")
>
> > Again, those who think in Python, will understand right away that:
>
> > math.count(x)
>
> > is counting the substring "x" in the "math" string. But can you see
> > where that might be confused to be a function called count() in the
> > math module?
>
> > I'm not complaining. Python is a great language in many respects. But,
> > I would take some issue with those claiming Python is intuitive and
> > easy. IMO: there seems to be many ambiguous, unintuitve, and
> > confusing, aspects to Python.
>
> These conversations are funny to me.  I use Python every day and I
> have never actually thought about the implications of binding objects
> to names, or two names pointing to the same object.  Problems of this
> sort just never come up in actual programming for me.  It just works.
>
> Python was my virgin language, so maybe that just makes it natural to
> me, but it seems like people coming from other languages get hung up
> on testing out the differences and theories rather than just
> programming in it.  Alas, maybe I have yet to get deep enough to run
> into these kinds of problems.
>
> The question of what math is in math.count(x) makes sense, but this
> one never comes up either (or rarely).  I usually know what the object
> is that I'm working with.
>
> ~Sean

After thought:

I do run into problems testing boolean values on a regular basis.
Probably should learn all the rules on them and use them properly, but
as a general rule I just don't use them, and test for the value
instead.

~Sean

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


Re: module error for elementtree

2007-05-11 Thread half . italian
On May 11, 12:05 am, [EMAIL PROTECTED] wrote:
> #!/usr/bin/env python
>
> from elementtree import ElementTree as Element
> tree = et.parse("testxml.xml")
>
> for t in tree.getiterator("SERVICEPARAMETER"):
> if t.get("Semantics") == "localId":
> t.set("Semantics", "dataPackageID")
>
> tree.write("output.xml")
>
> Hi,
>  For the above code to work elementtree is
> imported in first line ,but when running it says :
> ImportError: No module named elementtree.ElementTree
> Does thie module exists as default or a patch is needed?
> Thanks

http://groups.google.com/group/comp.lang.python/browse_frm/thread/e095cc79d1efb99/a4523a6e9b7061af?rnum=1#a4523a6e9b7061af

Read carefully.

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


Re: Path python versions and Macosx

2007-05-11 Thread half . italian
On May 11, 1:36 pm, andrea <[EMAIL PROTECTED]> wrote:
> Hi everyone,
> I use python on macosx with textmate as editor (great program).
>
> I also use macport to install unix programs from the command line and
> I find it great too.
> Well I would like to have all my modules in the path when I'm using
> textmate AND when I use the commandline (ipython), but because
> textmate and the command line use different python versions they also
> search in different places..
>
> I found somewhere to write .pythonrc.py like this
>
> #!/usr/bin/env python
> import sys
> PATH='/opt/local/lib/python2.4/site-packages/'
> sys.path.append(PATH)
> del sys
>
> But it doesn't work either, I also tried to append this
> PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/
> local/lib/python2.4/site-packages:${PATH}
> to .bash_profile but nothing.
>
> Where should I set this variables??
>
> Thanks a lot

You can set environment variables for gui apps with this freeware:
http://www.versiontracker.com/dyn/moreinfo/macosx/15073

You can edit some text files as well, but this thing just makes it
much easier.

~Sean

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


Re: os.popen on windows: loosing stdout of child process

2007-05-11 Thread half . italian
On May 11, 8:46 pm, Greg Ercolano <[EMAIL PROTECTED]> wrote:
> When I use os.popen(cmd,'w'), I find that under windows, the stdout
> of the child process disappears, instead of appearing in the DOS 
> window
> the script is invoked from. eg:
>
> C:\> type foo.py
> import os
> import sys
> file = os.popen("nslookup", 'w')
> file.write("google.com\n")
> file.close()
>
> C:\> python foo.py
> <-- nothing is printed
> C:\>
>
> This just seems wrong. The following DOS equivalent works fine:
>
> C:\> echo google.com | nslookup
> Default Server:  dns.erco.x
> Address:  192.168.1.14
> [..expected output..]
>
> When I run the same python program on a unix box, the output
> from 'nslookup' appears in the terminal, as I'd expect.
>
> Shouldn't popen() be consistent in its handling of the child's
> stdout and stderr across platforms?
>
> Maybe I'm missing something, being somewhat new to python, but
> an old hand at unix and win32 and functions like popen(). Didn't
> see anything in the docs for popen(), and I googled around quite
> a bit on the web and groups for eg. 'python windows popen stdout lost'
> and found nothing useful.
>
> FWIW, I'm using the windows version of python 2.5 from activestate.

Glad to see you're finally coming into the light Greg!  I've used Rush
in a few different studios over the past couple of years.  We even had
sushi once.  :)

I'm no expert like you, but I think I can point you in the right
direction.  You need os.popen2 which returns a tuple of file-like
objects. The first pointing to stdin, and the second pointing to
stdout.  Write to stdin, and read from stdout.

import os
import sys
stdin, stdout = os.popen2("nslookup")
stdin.write("google.com\n")
stdin.close()

print stdout.read()
stdout.close()

I don't use windows much, but I believe the os.popen functionality is
being replaced by subprocess.Popen:

from subprocess import *
import sys

p = Popen("nslookup", shell=True, bufsize=1024, stdin=PIPE,
stdout=PIPE, close_fds=True)
p.stdin.write("google.com\n")
p.stdin.close()

print p.stdout.read()
p.stdout.close()

I found these:
http://pydoc.org/2.4.1/subprocess.html
http://docs.python.org/lib/module-subprocess.html

~Sean DiZazzo
Curious George

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


Re: Creating a function to make checkbutton with information from a list?

2007-05-12 Thread half . italian
On May 12, 11:04 am, Thomas Jansson <[EMAIL PROTECTED]> wrote:
> Dear all
>
> I am writing a program with tkinter where I have to create a lot of
> checkbuttons. They should have the same format but should have
> different names. My intention is to run the functions and the create
> all the buttons with the names from the list.
>
> I now the lines below doesn't work, but this is what I have so far. I
> don't really know how call the element in the dict use in the for
> loop. I tried to call +'item'+ but this doesn't work.
>
> def create_checkbox(self):
>self.checkbutton = ["LNCOL", "LFORM", "LPOT", "LGRID",  "LERR",
> "LCOMP"]
>for item in self.checkbutton:
>   self.+'item'+Checkbutton = Chekcbutton(frame, onvalue='t',
> offvalue='f', variable=self.+'item'+)
>   self.+'item'+Checkbutton.grid()
>
> How should I do this?
>
> Kind regards
> Thomas Jansson

You can use exec("self." + name + " = " + value) to do what you want,
but then you need to exec() each time you want to access the
variable.  I think it is much better to create a class.

Here's what I came up with:

from Tkinter import *

class Window(Frame):
def __init__(self, parent=None):
Frame.__init__(self,parent=None)
self.names = ["LNCOL", "LFORM", "LPOT", "LGRID",  "LERR", 
"LCOMP",
"Sean"]
self.checkbuttons = []

self.f = Frame(root)
for name in self.names:
self.checkbuttons.append(CButton(parent=self.f, 
name=name,
default="f"))

self.f.pack(side="top",padx=5, pady=5)


class CButton(object):
def __init__(self, parent=None, name=None, default=None):
self.name = name
self.parent = parent
self.variable = StringVar()
self.variable.set(default)
self.checkbutton = None
self.create_checkbox(name)

def create_checkbox(self,name):
f = Frame(self.parent)
Label(f, text=name).pack(side="left")
self.checkbutton  = Checkbutton(f, onvalue='t', offvalue='f',
variable=self.variable)
self.checkbutton.bind("", self.state_changed)
self.pack()
f.pack()

def pack(self):
self.checkbutton.pack()

def state_changed(self, event=None):
print "%s: %s" % (self.name, self.variable.get())

if __name__ == '__main__':
root = Tk()
Window().mainloop()

~Sean

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


Re: __dict__ for instances?

2007-05-12 Thread half . italian
On May 12, 5:20 pm, Ivan Voras <[EMAIL PROTECTED]> wrote:
> While using PyGTK, I want to try and define signal handlers
> automagically, without explicitly writing the long dictionary (i.e. I
> want to use signal_autoconnect()).
>
> To do this, I need something that will inspect the current "self" and
> return a dictionary that looks like:
>
> {
>   "method_name" : self.method_name
>
> }
>
> Class.__dict__ does something very similar, but when I use it, either
> I'm doing something wrong or it doesn't return methods bound to "self",
> and python complains a wrong number of arguments is being passed to the
> methods (one instead of two).
>
> instance.__dict__ on the other hand returns an empty dictionary.
>
> This looks like it should be easy, but I can't find the solution :(
>
> --
> (\__/)
> (O.o)
> (> < )
>
> This is Bunny.
> Copy Bunny into your signature to help him on his way to world domination!
>
>  signature.asc
> 1KDownload

I think you want "dir(instance)"  __dict__ returns the instance
variables and values as a dictionary, but doesn't return methods.
dir() returns a list of the instance's methods and variables.  Then
you'd need to iterate over the list with type() looking for instance
methods

instance = Class.Class()
dict = {}
methods = [f for f in dir(instance) if str(type(instance.f)) == ""]
for m in methods:
dict[m.name] = m

The above is untested. I'm sure there is a better way to do this.

~Sean

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


Re: __dict__ for instances?

2007-05-13 Thread half . italian
On May 13, 4:30 am, Ivan Voras <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I think you want "dir(instance)"  __dict__ returns the instance
>
> Part of the problem is that dir(instance) returns a list of strings, so
> iterating the dir(instance) gets me strings, not methods. Alternatively,
> is there a way to get a "bound" instance by its name - some
> introspection function perhaps?
>
> > variables and values as a dictionary, but doesn't return methods.
>
> It does on a Class :(
>
> --
> (\__/)
> (O.o)
> (> < )
>
> This is Bunny.
> Copy Bunny into your signature to help him on his way to world domination!
>
>  signature.asc
> 1KDownload

I tried.

~Sean

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


Re: Removing part of string

2007-05-14 Thread half . italian
On May 13, 10:56 pm, [EMAIL PROTECTED] wrote:
> Hi,
> I am parsing an xml file ,and one part of structure looks
> something like this:
>
> -  PhysicalLink="Infotainment_Control_Bus_CAN">
>   Infotainment_Control_Bus_CAN_TIMEOUT_AX
>   Timeout N_As/N_Ar
>   Time from transmit request until a CAN frame transmit
> confirmation is received.
>   
>
>   In my code i am extracting the data within
> ,which is Timeout N_As/N_Ar.These tags repeat and will have
> different timer names..like
>
> -  PhysicalLink="Infotainment_Control_Bus_CAN">
>   Infotainment_Control_Bus_CAN_TIMEOUT_BS
>   Timeout N_Bs
>   Time that the transmitter of a multi-frame message
> shall wait to receive a flow control (FC) frame before timing out with
> a network layer error.
>   
>
>  I need to remove the words Timeout from the data,and
> take only the abbrevation..i.e.N_As/N_bs like that .In short i have to
> remove the words which come with name Time,and also the space which
> comes next to it.
> and take only the abbreviation.Can someone help me in this.
>  Thanks

Did you get elementtree working?

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


Re: Path python versions and Macosx

2007-05-14 Thread half . italian
On May 14, 4:46 am, andrea <[EMAIL PROTECTED]> wrote:
> On 12 Mag, 01:09, [EMAIL PROTECTED] wrote:
>
>
>
> > On May 11, 1:36 pm, andrea <[EMAIL PROTECTED]> wrote:
>
> > > Hi everyone,
> > > I use python on macosx with textmate as editor (great program).
>
> > > I also use macport to install unix programs from the command line and
> > > I find it great too.
> > > Well I would like to have all my modules in the path when I'm using
> > > textmate AND when I use the commandline (ipython), but because
> > > textmate and the command line use different python versions they also
> > > search in different places..
>
> > > I found somewhere to write .pythonrc.py like this
>
> > > #!/usr/bin/env python
> > > import sys
> > > PATH='/opt/local/lib/python2.4/site-packages/'
> > > sys.path.append(PATH)
> > > del sys
>
> > > But it doesn't work either, I also tried to append this
> > > PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:/opt/
> > > local/lib/python2.4/site-packages:${PATH}
> > > to .bash_profile but nothing.
>
> > > Where should I set this variables??
>
> > > Thanks a lot
>
> > You can set environment variables for gui apps with this 
> > freeware:http://www.versiontracker.com/dyn/moreinfo/macosx/15073
>
> > You can edit some text files as well, but this thing just makes it
> > much easier.
>
> > ~Sean
>
> Ok thanks, but why it doesn't work setting the .bash_profile?? What
> should I set manually theorically?? The problem is also that I have
> many modules for python 2.4 and trying to import them from the 2.5 of
> course gives errors..
> I installed them with macports (compiling), how can I make them switch
> to 2.5???
> thanks

Gui applications are not launched through the bash shell.
The .bash_profile never gets read.

You can accomplish the same thing as the freewware app I mentioned by
editing the xml file at ~/.MacOSX/environment.plist.  Its a simple xml
file with keys and their corresponding values.

Not sure about the modules.  You can force a script to look for libs
in a given directory like you mentioned, but that needs to go at the
top of each python file instead of a .pythonrc file.  Maybe the
modules will work with 2.5, maybe not.

~Sean

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


Re: removing spaces between 2 names

2007-05-14 Thread half . italian
On May 14, 11:00 pm, [EMAIL PROTECTED] wrote:
> Hi,
>  Suppose i have a string stored in variable,how do i remove the
> space between them,like if i have the name:
> "USDT request" in a variable.i need "USDTrequest",without any space .
> Thanks

s = "jk hij ght"
print "".join(s.split(" "))

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


Re: Trying to choose between python and java

2007-05-15 Thread half . italian
>> #3 Is there any equivalent to jfreechart and jfreereport
>> (http://www.jfree.org for details) in python.

ChartDirector
http://www.advsofteng.com/download.html

Again, not free for commercial use, but very versatile.

~Sean

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


Re: transparent images

2007-05-15 Thread half . italian
On May 15, 5:26 pm, [EMAIL PROTECTED] wrote:
> Does any one know how to make a transparent image with specifically
> PIL, but any standard python library will do. I need a spacer, and it
> has to be transparent.
>
> Thanks

Something like this...not my code...untested...

im = Image.open("image.jpg")
opacity = .5
if im.mode != 'RGBA':
im = im.convert('RGBA')
else:
im = im.copy()

alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alpha)

~Sean

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


Re: setting an attribute

2007-05-16 Thread half . italian
On May 16, 12:34 am, 7stud <[EMAIL PROTECTED]> wrote:
> "When you bind (on either a class or an instance) an attribute whose
> name is not special...you affect only the __dict__ entry for the
> attribute(in the class or instance, respectively)."
>
> In light of that statement, how would one explain the output of this
> code:
>
> class Test(object):
> x = [1, 2]
>
> def __init__(self):
> self.x[0] = 10
>
> print Test.__dict__#{.'x':[1,2]}
> t = Test()
> print t.x  #[10, 2]
> print t.__dict__   #{}
> print Test.__dict__#{.'x':[10,2]...}
>
> It looks to me like self.x[0] is binding on an instance whose
> attribute name is not special, yet it doesn't affect any __dict__
> entry for the attribute in the instance--instead it is affecting a
> __dict__ entry for the attribute in the class.

I think it's following scope rules.  It can't find an attribute for
self.x in the instance.  It then checks the class for the var and
finds it and sets it there.  It would error otherwise...

>>> class Test(object):
... def __init__(self):
... self.x[0] =7
...
>>> t = Test()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in __init__
AttributeError: 'Test' object has no attribute 'x'

~Sean

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


Re: iteration doesn't seem to work ??

2007-05-16 Thread half . italian
On May 16, 1:41 am, stef <[EMAIL PROTECTED]> wrote:
> hello,
>
> can someone tell me why the following iteration doesn't work,
> and
> how I should replace empty strings in a list with a default value.
>
>  >>> v
> ['123', '345', '', '0.3']
>  >>> for items in v:
> ...   if items=='':
> ...   items='3'
> ...
>  >>>
>  >>> v
> ['123', '345', '', '0.3']
>  >>>
>
> thanks,
> Stef Mientki

Inside the loop, 'items' is no longer referencing the list...its a
string.

>>> v = ['123', '4', '567', '']
>>> for i in v:
... print type(i)
...
...

This works

>>> for j,i in enumerate(v):
... if i=='':
... v[j] = '3'
...
>>> v
['123', '4', '567', '3']
>>>

~Sean

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


Re: How to do basic CRUD apps with Python

2007-05-16 Thread half . italian
On May 14, 7:46 pm, "James T. Dennis" <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> > walterbyrd a ?crit :
> >> With PHP, libraries, apps, etc. to do basic CRUD are everywhere. Ajax
> >> and non-Ajax solutions abound.
> >> With Python, finding such library, or apps. seems to be much more
> >> difficult to find.
> >> I thought django might be a good way, but I can not seem to get an
> >> answer on that board.
> >> I would like to put together a CRUD grid with editable/deletable/
> >> addable fields, click on the headers to sort. Something that would
> >> sort-of looks like an online  spreadsheet. It would be nice if the
> >> fields could be edited in-line, but it's not entirely necessary.
> >> Are there any Python libraries to do that sort of thing? Can it be
> >> done with django or cherrypy?
> > You may want to have a look at turbogears's widgets.
>
>  Admittedly I had to look up the meaning of CRUD in this context:
>  (http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete
>  create, read, update, and delete).
>
>  I'm looking at Turbogears' Widgets in another window as I type
>  this ... but it will be awhile before I can comment on how they
>  might apply to the OP's needs.  Actually I'm wholly unqualified
>  to comment on his or her needs ... but I can comment on how I
>  interpreted the question.
>
>  Even with the SQLAlchemy SQLSoup examples there's still an
>  annoying about of boilerplate coding that has to be done in order
>  to create a web application for doing CRUD on a database.
>
>  The missing element seems to be the ability to autogenerate
>  web forms and reports with the requisite controls in them.
>
>  Imagine, for a moment, being able to do something like:
>
> >>> import sqlalchemy.ext.webcrud as crud
> >>> db = crud.open()
> >>> db.displayTopForm()
> ' 
> '
>
>  ... and having a default "top level" web page generated with
>  options to query the database (or some specific table in the
>  database to be more specific, add new entries, etc).
>
>  I'm thinking of some sort of class/module that would generate
>  various sorts of HTML forms by default, but also allow one to
>  sub-class each of the form/query types to customize the contents.
>
>  It would use introspection on the database columns and constraints
>  to automatically generate input fields for each of the columns and
>  even fields for required foreign keys (or links to the CRUD for those
>  tables?).  Ideally it would also automatically hide autogenerated
>  (index/key) fields, and map the table column IDs to form names (with
>  gettext support for l10n of those).
>
>  I think that's the sort of thing the OP was looking for.  Not the
>  ORM ... the the glue between the web framework and the ORM.
>
> --
> Jim Dennis,
> Starshine: Signed, Sealed, Delivered

Sounds like you're talking about rails.  Do any of the python packages
compare with the ease of rails?  I got in just deep enough to see the
possibilities of it, and then had to stop to do real work in php.  I'd
be very interested in Python on Rails!

~Sean

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


Re: i/o prob revisited

2007-05-18 Thread half . italian
On May 18, 12:06 am, [EMAIL PROTECTED] wrote:
> Hi,
> I am parsing an xml file ,before that i have replaced a string in
> the original xml file with another and made a new xml file which will
> now be parsed.I am also opening some more files for output.The
> following code shows some i/o commands.
> file_input = raw_input("Enter The ODX File Path:")
> input_xml = open(file_input,'r')
>
> (shortname,ext)=os.path.splitext(file_input)
> f_open_out=shortname+".ini"
> log=shortname+".xls"
> test_file=shortname+"testxml.xml"
>
> saveout = sys.stdout
>
> xmlcont=input_xml.read()
> input_xml.close()
>
> xmlcont=xmlcont.replace('localId','dataPackageId')
>
> output_file = open(test_file,"w")
> output_file.write(xmlcont)
> output_file.close()
>
> f_open=open(f_open_out, 'w')
> logfile=open(log,"w")
> sys.stdout = f_open
>
>  After this i have to parse the new xml file which is in
> output_file .hence
>
> input_xml_sec = open(output_file,'r')
> xmldoc = minidom.parse(input_xml_sec)
>
>   But i am getting an error on this line
> (input_xml_sec = open(output_file,'r')).I have tried to figure out
> but
> not able to debug.Can someone throw some light or anything they feel
> could be going wrong somewhere.
>   How do i capture the error as it vanishes very
> qucikly when i run through command prompt,(the idle envir gives
> indentation errors for no reason(which runs perfectly from cmd
> prompt),hence i dont run using conventional F5.

http://docs.python.org/tut/

Read carefully.

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm looking for any existing packages or ideas on how to implement the
> equivalent of a generator (in the Python sense, 
> i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> way. As a use case, imagine a function that generates a range of
> primes. I'd like to be able to do something along the following lines:
>
> def iterprimes(start=1, end=None):
># ...
>yield prime
>
> # rpc-related initialization
> ...
> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> for prime in proxy:
> print prime
>
> Is there any module out there that does anything close to this ?
>
> George

Parellel Python?

http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES

I've never used it, but looks like it does what you are looking for.

~Sean

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm looking for any existing packages or ideas on how to implement the
> equivalent of a generator (in the Python sense, 
> i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> way. As a use case, imagine a function that generates a range of
> primes. I'd like to be able to do something along the following lines:
>
> def iterprimes(start=1, end=None):
># ...
>yield prime
>
> # rpc-related initialization
> ...
> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> for prime in proxy:
> print prime
>
> Is there any module out there that does anything close to this ?
>
> George

Parellel Python?

http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES

I've never used it, but looks like it does what you are looking for.

~Sean

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm looking for any existing packages or ideas on how to implement the
> equivalent of a generator (in the Python sense, 
> i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> way. As a use case, imagine a function that generates a range of
> primes. I'd like to be able to do something along the following lines:
>
> def iterprimes(start=1, end=None):
># ...
>yield prime
>
> # rpc-related initialization
> ...
> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> for prime in proxy:
> print prime
>
> Is there any module out there that does anything close to this ?
>
> George

Parellel Python?

http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES

I've never used it, but looks like it does what you are looking for.

~Sean

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm looking for any existing packages or ideas on how to implement the
> equivalent of a generator (in the Python sense, 
> i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> way. As a use case, imagine a function that generates a range of
> primes. I'd like to be able to do something along the following lines:
>
> def iterprimes(start=1, end=None):
># ...
>yield prime
>
> # rpc-related initialization
> ...
> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> for prime in proxy:
> print prime
>
> Is there any module out there that does anything close to this ?
>
> George

Parellel Python?

http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES

I've never used it, but looks like it does what you are looking for.

~Sean

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm looking for any existing packages or ideas on how to implement the
> equivalent of a generator (in the Python sense, 
> i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> way. As a use case, imagine a function that generates a range of
> primes. I'd like to be able to do something along the following lines:
>
> def iterprimes(start=1, end=None):
># ...
>yield prime
>
> # rpc-related initialization
> ...
> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> for prime in proxy:
> print prime
>
> Is there any module out there that does anything close to this ?
>
> George

DOLT!

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm looking for any existing packages or ideas on how to implement the
> equivalent of a generator (in the Python sense, 
> i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> way. As a use case, imagine a function that generates a range of
> primes. I'd like to be able to do something along the following lines:
>
> def iterprimes(start=1, end=None):
># ...
>yield prime
>
> # rpc-related initialization
> ...
> rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> for prime in proxy:
> print prime
>
> Is there any module out there that does anything close to this ?
>
> George

Parellel Python?

http://www.parallelpython.com/content/view/17/31/#SUM_PRIMES

I've never used it, but looks like it does what you are looking for.

~Sean

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


Re: Parallel/distributed generator

2007-05-23 Thread half . italian
On May 23, 1:22 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On May 23, 2:58 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > On May 23, 11:00 am, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > > I'm looking for any existing packages or ideas on how to implement the
> > > equivalent of a generator (in the Python sense, 
> > > i.e.http://www.python.org/dev/peps/pep-0255/) in a parallel/distributed
> > > way. As a use case, imagine a function that generates a range of
> > > primes. I'd like to be able to do something along the following lines:
>
> > > def iterprimes(start=1, end=None):
> > ># ...
> > >yield prime
>
> > > # rpc-related initialization
> > > ...
> > > rpc_proxy = some_rpc_lib(iterprimes, start=1e6, end=1e12)
> > > for prime in proxy:
> > > print prime
>
> > > Is there any module out there that does anything close to this ?
>
> > > George
>
> > DOLT!- Hide quoted text -
>
> > - Show quoted text -
>
> I thought you were making a joke about parallel processing.
> I thought you were making a joke about parallel processing.
> I thought you were making a joke about parallel processing.
> I thought you were making a joke about parallel processing.
>
> -- Paul

Damn computers!

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


Re: sockets, gethostname() changing

2007-05-24 Thread half . italian
On May 24, 8:04 pm, 7stud <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm experimenting with a basic socket program(from a book), and both
> the client and server programs are on my computer.   In both programs,
> I call socket.gethostname(), but I discovered that when I am connected
> to the internet, both the client and server hang and nothing happens.
> I discovered that the hostname of my computer automatically changes to
> that of my isp when I'm connected to the internet, and presumably the
> server program on my computer cannot listen on my isp's address(host,
> port).   Is there a way to make the hostname of my computer static, so
> that it doesn't change to my isp's hostname when I connect to the
> internet.  I'm using mac os 10.4.7.  Why does my computer's hostname
> dynamically change in the first place?
>
> server program:
> ---
> import socket
>
> s = socket.socket()
>
> host = socket.gethostname()
> print host
> port = 1274
> s.bind((host, port))
>
> s.listen(5)
> while("Ctrl-C hasn't been entered"):
> c, addr = s.accept()   #blocks and waits for client connection
> print "Got socket connection from", addr
> c.send("Thank you for connecting.  Now get lost.")
> c.close()
>
> client program:
> ---
> import socket
>
> s = socket.socket()
>
> host = socket.gethostname()
> port = 1274
>
> s.connect((host, port))
> print s.recv(1024)
> s.close()

I can't imagine why your hostname would be changing, unless you
installed some of their proprietary software thats messing around with
things.  What is the hostname set to in Sys Prefs->Sharing?  Try
setting it there.  What are the before and after connection names you
get?

~Sean

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


Re: sockets, gethostname() changing

2007-05-25 Thread half . italian
On May 24, 8:50 pm, 7stud <[EMAIL PROTECTED]> wrote:
> Thanks for the response.
>
> On May 24, 9:24 pm, [EMAIL PROTECTED] wrote:
>
> > I can't imagine why your hostname would be changing, unless you
> > installed some of their proprietary software thats messing around with
> > things.  
>
> When I first started using Terminal, I noticed that the prompt in
> Terminal changed when I was connected to the internet.
>
> > What is the hostname set to in Sys Prefs->Sharing?  
>
> My Name's Computer
>
> > Try
> > setting it there.  What are the before and after connection names you
> > get?
>
> If I add the line:
>
> host = socket.gethostname()
> print host   #<--
>
> and I'm not connected to the internet and I run the program, I get:
>
> my-names-computer.local
>
> When I'm connected to the internet, I get:
>
> dialup-9.999.999.999.dial9.xxx.level9.net

That would bug me to high hell.  A router in the middle would probably
stop that.


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


Re: sockets, gethostname() changing

2007-05-25 Thread half . italian
On May 24, 8:04 pm, 7stud <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm experimenting with a basic socket program(from a book), and both
> the client and server programs are on my computer.   In both programs,
> I call socket.gethostname(), but I discovered that when I am connected
> to the internet, both the client and server hang and nothing happens.
> I discovered that the hostname of my computer automatically changes to
> that of my isp when I'm connected to the internet, and presumably the
> server program on my computer cannot listen on my isp's address(host,
> port).   Is there a way to make the hostname of my computer static, so
> that it doesn't change to my isp's hostname when I connect to the
> internet.  I'm using mac os 10.4.7.  Why does my computer's hostname
> dynamically change in the first place?
>
> server program:
> ---
> import socket
>
> s = socket.socket()
>
> host = socket.gethostname()
> print host
> port = 1274
> s.bind((host, port))
>
> s.listen(5)
> while("Ctrl-C hasn't been entered"):
> c, addr = s.accept()   #blocks and waits for client connection
> print "Got socket connection from", addr
> c.send("Thank you for connecting.  Now get lost.")
> c.close()
>
> client program:
> ---
> import socket
>
> s = socket.socket()
>
> host = socket.gethostname()
> port = 1274
>
> s.connect((host, port))
> print s.recv(1024)
> s.close()

Try setting an environment variable for 'hostname' using this:
http://www.versiontracker.com/dyn/moreinfo/macosx/15073

Either way, its a good program to have.

~Sean

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


Re: Can python create a dictionary from a list comprehension?

2007-05-27 Thread half . italian
On May 27, 1:55 pm, erikcw <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to turn o list of objects into a dictionary using a list
> comprehension.
>
> Something like
>
> entries = {}
>  [entries[int(d.date.strftime('%m'))] = d.id] for d in links]
>
> I keep getting errors when I try to do it.  Is it possible?  Do
> dictionary objects have a method equivalent to [].append?  Maybe a
> lambda?
>
> Thanks for your help!
> Erik

try...

[entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in
links]

btw...I was curious of this too.  I used 'dir(dict)' and looked for a
method that might do what we wanted and bingo!

~Sean

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread half . italian
On May 28, 12:25 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>, half.italian
> wrote:
>
> > [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in
> > links]
>
> > btw...I was curious of this too.  I used 'dir(dict)' and looked for a
> > method that might do what we wanted and bingo!
>
> This is really ugly.  Except `__init__()` it's always a code smell if you
> call a "magic" method directly instead of using the corresponding
> syntactic sugar or built in function.  And using a list comprehension just
> for side effects is misleading because the reader expects a (useful) list
> to be build when stumbling over a list comp and it's wasteful because an
> unnecessary list of `None`\s is build and thrown away for no reason other
> than to have a one liner.  This is not Perl!  ;-)
>
> Ciao,
> Marc 'BlackJack' Rintsch

It's ugly I agree, but it was the first solution I found.  I need you
guys for the _right_ solutions :)  I have stumbled over the same
situation myself.  I don't see that the list comprehension itself is
misleading.  If nothing is catching the empty list that is returned,
it signals that the returned list is unimportant, and if wrapped by a
call to dict() its obvious also.

Do you think we just shouldn't use list comprehensions to build
dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?

~Sean

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


Re: User input with a default value that can be modified

2007-05-28 Thread half . italian
On May 28, 11:52 am, "Etienne Hilson" <[EMAIL PROTECTED]>
wrote:
> Hello the list :-)
>
> I do a little program that permit the user to manage list of sentences.
> This program runs into a linux shell.
> The user can add, modify and delete the sentences.
>
> What I want to do is :
>
> When the user want to modify one sentence, I would like to do this :
>
> Modify your sentence : The_sentence_appear_here_followed_by_a_cursor
>
> And the user can go back with the cursor, like in the bash shell,
> delete, modify, and when pressing enter, the new value (or the same if
> not modified) is put in my variable.
>
> Of course, the first think I did as a newbie was :
>
> new_sentence = raw_input("Modify your sentence : "old_sentence)
>
> But OF COURSE, stupid am I, the user cannot put the cursor back into
> the old sentence !
>
> I think about playing with some sophisticated keyboard exercise where
> I could program a new input command with a value already appearing as
> answer, but I am pretty sure that it exists already.
>
> What do you think about it ?
>
> Actually, it is quite difficult to find anything on it, because the
> keywords are not very obvious (input, default answer, ...)
>
> Thank you for your help.
>
> Etienne
> --
> (\__/)
> (='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
> (")_(")  votre signature pour l'aider à dominer le monde

Check into the readline module.  This is what I came up with.  A
second thread injects the text into the open readline instance.
Hopefully the experts will show the _right_ way to do it.

import readline, threading
import time

class write(threading.Thread):
def __init__ (self, s):
threading.Thread.__init__(self)
self.s = s

def run(self):
time.sleep(.01)
readline.insert_text(self.s)
readline.redisplay()

write("Edit this sentence").start()
s = raw_input("prompt:")

print s

~Sean

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


Re: User input with a default value that can be modified

2007-05-28 Thread half . italian
On May 28, 11:52 am, "Etienne Hilson" <[EMAIL PROTECTED]>
wrote:
> Hello the list :-)
>
> I do a little program that permit the user to manage list of sentences.
> This program runs into a linux shell.
> The user can add, modify and delete the sentences.
>
> What I want to do is :
>
> When the user want to modify one sentence, I would like to do this :
>
> Modify your sentence : The_sentence_appear_here_followed_by_a_cursor
>
> And the user can go back with the cursor, like in the bash shell,
> delete, modify, and when pressing enter, the new value (or the same if
> not modified) is put in my variable.
>
> Of course, the first think I did as a newbie was :
>
> new_sentence = raw_input("Modify your sentence : "old_sentence)
>
> But OF COURSE, stupid am I, the user cannot put the cursor back into
> the old sentence !
>
> I think about playing with some sophisticated keyboard exercise where
> I could program a new input command with a value already appearing as
> answer, but I am pretty sure that it exists already.
>
> What do you think about it ?
>
> Actually, it is quite difficult to find anything on it, because the
> keywords are not very obvious (input, default answer, ...)
>
> Thank you for your help.
>
> Etienne
> --
> (\__/)
> (='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
> (")_(")  votre signature pour l'aider à dominer le monde

Check into the readline module.  This is what I came up with.  A
second thread injects the text into the open readline instance.
Hopefully the experts will show the _right_ way to do it.

import readline, threading
import time

class write(threading.Thread):
def __init__ (self, s):
threading.Thread.__init__(self)
self.s = s

def run(self):
time.sleep(.01)
readline.insert_text(self.s)
readline.redisplay()

write("Edit this sentence").start()
s = raw_input("prompt:")

print s

~Sean

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


Re: multiline regular expression (replace)

2007-05-29 Thread half . italian
On May 29, 2:03 am, Zdenek Maxa <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I would like to perform regular expression replace (e.g. removing
> everything from within tags in a XML file) with multiple-line pattern.
> How can I do this?
>
> where = open("filename").read()
> multilinePattern = "^  <\/tag>$"
> re.search(multilinePattern, where, re.MULTILINE)
>
> Thanks greatly,
> Zdenek

Why not use an xml package for working with xml files?  I'm sure
they'll handle your multiline tags.

http://effbot.org/zone/element-index.htm
http://codespeak.net/lxml/

~Sean

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


Re: paste text with newlines into raw_input?

2007-05-30 Thread half . italian
On May 30, 2:04 pm, BartlebyScrivener <[EMAIL PROTECTED]> wrote:
> Using Python on Debian Etch.
>
> What is the best way to paste a block of text in at the command
> prompt.
>
> I'm trying something like:
>
> Quote = raw_input("Paste quote here: ")
>
> Which works great for one line of text with a single newline. It gets
> stripped. Okay.
>
> Is there a way to paste in a block of text that has multiple lines and
> newlines? I don't care if they all get stripped in the process, in
> fact I'd prefer it. I've used strip before, but that doesn't seem to
> work until you get the text into the program.
>
> Thanks for any help.
>
> Rick

import sys
s =sys.stdin.read()
print s

which will read until ctrl-d

~Sean

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


Threaded Design Question

2007-08-09 Thread half . italian
Hi all!  I'm implementing one of my first multithreaded apps, and have
gotten to a point where I think I'm going off track from a standard
idiom.  Wondering if anyone can point me in the right direction.

The script will run as a daemon and watch a given directory for new
files.  Once it determines that a file has finished moving into the
watch folder, it will kick off a process on one of the files.  Several
of these could be running at any given time up to a max number of
threads.

Here's how I have it designed so far.  The main thread starts a
Watch(threading.Thread) class that loops and searches a directory for
files.  It has been passed a Queue.Queue() object (watch_queue), and
as it finds new files in the watch folder, it adds the file name to
the queue.

The main thread then grabs an item off the watch_queue, and kicks off
processing on that file using another class Worker(threading.thread).

My problem is with communicating between the threads as to which files
are currently processing, or are already present in the watch_queue so
that the Watch thread does not continuously add unneeded files to the
watch_queue to be processed.  For example...Watch() finds a file to be
processed and adds it to the queue.  The main thread sees the file on
the queue and pops it off and begins processing.  Now the file has
been removed from the watch_queue, and Watch() thread has no way of
knowing that the other Worker() thread is processing it, and shouldn't
pick it up again.  So it will see the file as new and add it to the
queue again.  PS.. The file is deleted from the watch folder after it
has finished processing, so that's how i'll know which files to
process in the long term.

I made definite progress by creating two queues...watch_queue and
processing_queue, and then used lists within the classes to store the
state of which files are processing/watched.

I think I could pull it off, but it has got very confusing quickly,
trying to keep each thread's list and the queue always in sync with
one another.  The easiset solution I can see is if my threads could
read an item from the queue without removing it from the queue and
only remove it when I tell it to.  Then the Watch() thread could then
just follow what items are on the watch_queue to know what files to
add, and then the Worker() thread could intentionally remove the item
from the watch_queue once it has finished processing it.

Now that I'm writing this out, I see a solution by over-riding or
wrapping Queue.Queue().get() to give me the behavior I mention above.

I've noticed .join() and .task_done(), but I'm not sure of how to use
them properly.  Any suggestions would be greatly appreciated.

~Sean

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


Re: tempfile behavior

2007-08-09 Thread half . italian
On Aug 9, 11:21 am, billiejoex <[EMAIL PROTECTED]> wrote:
> Hi all,
> I would like to use tempfile module to generate files having unique
> names excepting that I don't want them to be removed after closing.
> Does it is possible?

Looks like tempfile.mkstemp() will do what you want.

'''Unlike TemporaryFile(), the user of mkstemp() is responsible for
deleting the temporary file when done with it.'''

~Sean

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


Re: Threaded Design Question

2007-08-09 Thread half . italian
On Aug 9, 12:09 pm, "Justin T." <[EMAIL PROTECTED]> wrote:
> On Aug 9, 11:25 am, [EMAIL PROTECTED] wrote:
>
> > Here's how I have it designed so far.  The main thread starts a
> > Watch(threading.Thread) class that loops and searches a directory for
> > files.  It has been passed a Queue.Queue() object (watch_queue), and
> > as it finds new files in the watch folder, it adds the file name to
> > the queue.
>
> > The main thread then grabs an item off the watch_queue, and kicks off
> > processing on that file using another class Worker(threading.thread).
>
> Sounds good.
>
>
>
> > I made definite progress by creating two queues...watch_queue and
> > processing_queue, and then used lists within the classes to store the
> > state of which files are processing/watched.
>
> This sounds ugly, synchronization is one of those evils of
> multithreaded programming that should be avoided if possible. I see a
> couple of dirt simple solutions:
>
> 1. Have the watch thread move the file into a "Processing" folder that
> it doesn't scan
> 2. Have the watch thread copy the file into a python tempfile object
> and push that onto the queue, then delete the real file. This can be
> done efficiently (well, more efficiently than new.write(old.read())
> with shutil.copyfileobj(old, new)
>
> Both those take very few lines of code, don't require synchronization,
> and don't require extending standard classes.

Thanks foor the ideas Justin.

I started subclassing/extending the Queue.Queue object with two
additional classes.  One to return the first item in the list without
removing it from the queue, and one to return all items of the list
without removing them.  I think this will take me to where I want to
go.  If it doesn't work, I might just use your processing folder
approach.  That sounds the easiest, although I'm still interested in
any idioms or other proven approaches for this sort of thing.

~Sean

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


Re: Threaded Design Question

2007-08-10 Thread half . italian
On Aug 9, 9:45 pm, "Mark T" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
>
>
> > Hi all!  I'm implementing one of my first multithreaded apps, and have
> > gotten to a point where I think I'm going off track from a standard
> > idiom.  Wondering if anyone can point me in the right direction.
>
> > The script will run as a daemon and watch a given directory for new
> > files.  Once it determines that a file has finished moving into the
> > watch folder, it will kick off a process on one of the files.  Several
> > of these could be running at any given time up to a max number of
> > threads.
>
> > Here's how I have it designed so far.  The main thread starts a
> > Watch(threading.Thread) class that loops and searches a directory for
> > files.  It has been passed a Queue.Queue() object (watch_queue), and
> > as it finds new files in the watch folder, it adds the file name to
> > the queue.
>
> > The main thread then grabs an item off the watch_queue, and kicks off
> > processing on that file using another class Worker(threading.thread).
>
> > My problem is with communicating between the threads as to which files
> > are currently processing, or are already present in the watch_queue so
> > that the Watch thread does not continuously add unneeded files to the
> > watch_queue to be processed.  For example...Watch() finds a file to be
> > processed and adds it to the queue.  The main thread sees the file on
> > the queue and pops it off and begins processing.  Now the file has
> > been removed from the watch_queue, and Watch() thread has no way of
> > knowing that the other Worker() thread is processing it, and shouldn't
> > pick it up again.  So it will see the file as new and add it to the
> > queue again.  PS.. The file is deleted from the watch folder after it
> > has finished processing, so that's how i'll know which files to
> > process in the long term.
>
> > I made definite progress by creating two queues...watch_queue and
> > processing_queue, and then used lists within the classes to store the
> > state of which files are processing/watched.
>
> > I think I could pull it off, but it has got very confusing quickly,
> > trying to keep each thread's list and the queue always in sync with
> > one another.  The easiset solution I can see is if my threads could
> > read an item from the queue without removing it from the queue and
> > only remove it when I tell it to.  Then the Watch() thread could then
> > just follow what items are on the watch_queue to know what files to
> > add, and then the Worker() thread could intentionally remove the item
> > from the watch_queue once it has finished processing it.
>
> > Now that I'm writing this out, I see a solution by over-riding or
> > wrapping Queue.Queue().get() to give me the behavior I mention above.
>
> > I've noticed .join() and .task_done(), but I'm not sure of how to use
> > them properly.  Any suggestions would be greatly appreciated.
>
> > ~Sean
>
> Just rename the file.  We've used that technique in a similar application at
> my work for years where a service looks for files of a particular extension
> to appear in a directory.  When the service sees a file, in renames it to a
> different extension and spins off a thread to process the contents.
>
> -Mark T.

I ended up taking this route for the most part.  The worker thread
first moves the file to be processed into a temp directory, and the
watch thread never knows about it again.  I still had to implement my
StateQueue(Queue.Queue) so I could implement a function to return all
the items on the queue without popping them off.

Thanks all for your great ideas.  My current response to multi-
threading... PITA!

~Sean

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


Re: moving files in a seperate thread (and/or with progress?)

2007-08-15 Thread half . italian
On Aug 15, 2:28 am, "Jorgen Bodde" <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I want to make a small batch copy tool that scans for certain files,
> and copies them to a specified directory. Since the files are huge
> (AVI / DIVX) typical 300 to 700 Mb, I want to provide the user with
> some feedback during the file copy.
>
> Here is my dillemma; When I use shutil.move(..,..) I have to wait
> until it's done, there is no feedback, so the GUI basically hangs.
> However, shutil.move can be fast because it intelligently renames the
> file when it is on the same medium, but slow when it moves to a
> different one.
> When I use my own implementation of a move mechanism that provides
> feedback, I lose that intelligence, and I might slow down the copy
> process unneccessarily.
>
> When I move files, feedback is handy to have, but not neccesary so I
> thought I can also call shutil.move from a seperate thread so the main
> GUI stays responsive. What are my options in aborting a move by
> killing the thread or are there other (3rdparty) modules I might use
> to get better move or copy performances?
>
> Just opening the file, performing a block copy myself seems like it
> will slow down the transfer, but up until now I found no way to move
> or copy with progress or abilities to abort the file transfer..
>
> Any ideas?
>
> Regards,
> - Jorgen

The following link helped me to pull it off with Tkinter.  A
complicated example, but very well written.

http://uucode.com/texts/pylongopgui/pyguiapp.html

~Sean

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


Socket - gaierror

2007-08-27 Thread half . italian
Hi all,

I'm having trouble with the socket module resolving a hostname.  It
seems like this is a system level problem, but I'm not even sure where
to start.  I can ping the smtp server by name and IP, but when
smtp.SMTP("theHost") tries to get the hostname, it keeps giving me the
following error:

  File "bin/program.py", line 123, in notify
smtp = smtplib.SMTP("theHost")

  File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
addr = socket.gethostbyname(socket.gethostname())

gaierror: (-2, 'Name or service not known')

I tried changing to a different smtp server, using an ip instead of a
host name.  I could ping both boxes by name oor IP.

any ideas?

~Sean

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


Re: Socket - gaierror

2007-08-27 Thread half . italian
On Aug 27, 12:32 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi all,
>
> > I'm having trouble with the socket module resolving a hostname.  It
> > seems like this is a system level problem, but I'm not even sure where
> > to start.  I can ping the smtp server by name and IP, but when
> > smtp.SMTP("theHost") tries to get the hostname, it keeps giving me the
> > following error:
>
> >   File "bin/program.py", line 123, in notify
> > smtp = smtplib.SMTP("theHost")
>
> >   File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
> > addr = socket.gethostbyname(socket.gethostname())
>
> > gaierror: (-2, 'Name or service not known')
>
> > I tried changing to a different smtp server, using an ip instead of a
> > host name.  I could ping both boxes by name oor IP.
>
> > any ideas?
>
> > ~Sean
>
> The specific error shown is a DNS resolution problem.  Based on the
> URL "theHost" smtplib can't resolve to an IP address (which is what
> socket.gethostbyname does).  You don't say what happened when you changed to 
> ip,
> but I suspect it is a different error or some other problem.  Maybe a firewall
> issue (port 25 not open?), but I'm just guessing.
>
> -Larry

Changing it to IP gives me the same exact error...

  File "bin/prgram.py", line 123, in notify
smtp = smtplib.SMTP("XXX.XXX.XXX.XXX")

  File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
addr = socket.gethostbyname(socket.gethostname())

gaierror: (-2, 'Name or service not known')

Looks like the smtp port is closed on the client machine...doh Should
have gotten to that!

Thank you.

~Sean

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


Re: Socket - gaierror

2007-08-27 Thread half . italian
On Aug 27, 12:47 pm, [EMAIL PROTECTED] wrote:
> On Aug 27, 12:32 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > Hi all,
>
> > > I'm having trouble with the socket module resolving a hostname.  It
> > > seems like this is a system level problem, but I'm not even sure where
> > > to start.  I can ping the smtp server by name and IP, but when
> > > smtp.SMTP("theHost") tries to get the hostname, it keeps giving me the
> > > following error:
>
> > >   File "bin/program.py", line 123, in notify
> > > smtp = smtplib.SMTP("theHost")
>
> > >   File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
> > > addr = socket.gethostbyname(socket.gethostname())
>
> > > gaierror: (-2, 'Name or service not known')
>
> > > I tried changing to a different smtp server, using an ip instead of a
> > > host name.  I could ping both boxes by name oor IP.
>
> > > any ideas?
>
> > > ~Sean
>
> > The specific error shown is a DNS resolution problem.  Based on the
> > URL "theHost" smtplib can't resolve to an IP address (which is what
> > socket.gethostbyname does).  You don't say what happened when you changed 
> > to ip,
> > but I suspect it is a different error or some other problem.  Maybe a 
> > firewall
> > issue (port 25 not open?), but I'm just guessing.
>
> > -Larry
>
> Changing it to IP gives me the same exact error...
>
>   File "bin/prgram.py", line 123, in notify
> smtp = smtplib.SMTP("XXX.XXX.XXX.XXX")
>
>   File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
> addr = socket.gethostbyname(socket.gethostname())
>
> gaierror: (-2, 'Name or service not known')
>
> Looks like the smtp port is closed on the client machine...doh Should
> have gotten to that!
>
> Thank you.
>
> ~Sean

I take it back, that wasn't the solution.  I got it to work by
haacking smtplib with a static host instead of the
socket.gethostbyname(socket.gethostname()) call...but if I leave that
in there I might get shot one day.  What could cause the shell to be
able to resolve the addresses properly, but not python?
nnsswitch.conf ?

I don't know enough about what's going on in the background.  Any
other ideas? Or should I try this on a unix board?

~Sean

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


Re: Socket - gaierror

2007-08-27 Thread half . italian
On Aug 27, 4:22 pm, [EMAIL PROTECTED] (Douglas Wells) wrote:
> In article <[EMAIL PROTECTED]>,
>
>
>
>  [EMAIL PROTECTED] writes:
> > On Aug 27, 12:32 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
>
> > Changing it to IP gives me the same exact error...
>
> >   File "bin/prgram.py", line 123, in notify
> > smtp = smtplib.SMTP("XXX.XXX.XXX.XXX")
>
> >   File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
> > addr = socket.gethostbyname(socket.gethostname())
>
> > gaierror: (-2, 'Name or service not known')
>
> > Looks like the smtp port is closed on the client machine...doh Should
> > have gotten to that!
>
> > ~Sean
>
> Note that the lookup is of your *local* system name
> (socket.gethostname()).  I suspect that the name of your client
> system (the one running the python script) is not registered in
> DNS.
>
> Try ping'ing your own system and see if that resolves in DNS.  In
> UNIX/Linux you can use the hostname command; in any system you can
> write a python script to print the result of socket.gethostname().
>
>  - dmw
>
> --
> .   Douglas Wells .  Connection Technologies  .
> .   Internet:  -sp9804- -at - contek.com- .

I found a solution...but still not sure why that happened.

[EMAIL PROTECTED]:17:08:5E:EF:0F:/usr/local/sw/program/bin# hostname
00:17:08:5E:EF:0F
[EMAIL PROTECTED]:17:08:5E:EF:0F:/usr/local/sw/program/bin# ping 00:17:08:5E:EF:
0F
ping: unknown host 00:17:08:5E:EF:0F

>>> socket.gethostname()
'00:17:08:5E:EF:0F'

Workaround: pass the 'local_hostname' arg to the smtplib.SMTP() call
with "localhost"

ie smtp.SMTP("some.computer", local_hostname="localhost")

This is just overriding the socket.gethostname() call entirely.

Did a bit of testing with the /etc/hosts file, and even with an entry
to the hostname it can't resolve the ip.
The problem is the name "00:17:08:5E:EF:0F"  PS.  I didn't choose to
set the hostname that way.

~Sean

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


Re: Newbie question - sorting a slice

2007-08-28 Thread half . italian
On Aug 28, 7:43 pm, hwg <[EMAIL PROTECTED]> wrote:
> I've searched the group and didn't see the answer to this...
>
> Why doesn't this work?:
>
> >>> letters = ['d', 'a', 'e', 'c', 'b']
> >>> letters[1:3].sort()
>
> This returns None.
>
> Why?  letters[1:3]  is  ['a', 'e', 'c']Sorting that should return
> ['a', 'c', 'e']
>
> hwg

sort() works on a list in place, and returns none

You have to make a temp list.

note...
>>> letters = ['d', 'a', 'e', 'c', 'b']
>>> print letters.sort()
None
>>> print letters
['a', 'b', 'c', 'd', 'e']

~Sean

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


Re: Is there a simple way to exit a while loop on keystroke?

2007-08-31 Thread half . italian
On Aug 31, 11:11 am, gsxg <[EMAIL PROTECTED]> wrote:
> Thanks,
> The curses library doesn't look to helpful to me.  However using CTRL-
> C is fine and is working nicely.
>
> BTW, it should be "time.sleep(1)" in the example above, instead of
> just
> "sleep(1)"  (Just in case any other newbies like me read this)
>
> Thanks again

Depends on how you import 'time'

import time
time.sleep(1)

from time import sleep
sleep(1)

~Sean

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


Re: Python+Expect+Win32 = Not Possible?

2007-09-13 Thread half . italian
On Sep 12, 9:27 pm, gamename <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Is it still the case there is no practical Expect-like module for
> win32? I know that cygwin can support pexpect, but that isn't an
> option here --- I have to use a native win32 Python version.
>
> Are there alternatives, or is it simply not an option to replicate
> Expect on win32 with python?
>
> All I'm trying to do is start a couple processes, wait for each to say
> "done" on stdout and then quit (or timeout if something went wrong).
>
> TIA,
> -T

I had planned on using telnet to do the same thing on windows.  I
don't think I ever proved it, but I'm pretty sure it will work.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52228

~Sean

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


Circular Class Logic

2007-03-14 Thread half . italian
I have a set of classes that describe Files, Folders, etc., that I use
often in my scripts for moving files around, getting a files
extension, converting paths, changing permissions, etc  It's very
similar to Jason Orendorff's 'Path' library, and is very useful to
me.  The base class 'Data.py' stores all the basic attributes of any
piece of data on disk, and it is then subclassed to represent files
and folders with the attributes specific to that type of object.

I recently made a new class 'Disk.py' that is a subclass of
'Folder.py', to describe all of the attributes of any local or network
disks attached to the computer.  I subclassed it from Folder, because
it really is a folder, it's just at the root of a drive.  I'm
realizing that these 'Disk' objects are pretty useful, and I came up
with the idea to put a 'Disks' instance as a shared class variable
(singleton?) within the base class ('Data')  The idea being that any
instance of a File, or Folder object would contain the list of Disk
objects attached to the system, and could use them accordingly.  Also
important is that I would only need to gather the disk info once for
any given running application and all the instances could use it
(origianlly I was getting the disk info for each File/Folder object)

After an hour of banging my head from getting "AttributeError:
'module' object has no attribute 'Disks'" errors, I finally realized
that I'm trying to include an instance in the base class that is a
subclass of itself.  Short of making 'Disk' no longer a subclass of
Folder, is there any other way to include a subclassed instance in the
base class of that object? (this is very hard to put in to words)

~Sean

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


Re: Circular Class Logic

2007-03-14 Thread half . italian
>
> That is, each of the classes want to inherit from the others.

That's not exactly what I'm doing, but your comment still might help.
I actually want to include an instance of a subclass in it's
superclass like this:

= foo.py =
import Baz

class Foo:
baz = Baz.Baz()

def __init__(self):
pass
=

= bar.py =
import Foo

class Bar(Foo.Foo):
pass
=

= baz.py =
import Bar

class Baz(Bar.Bar):
pass
=

> The usual solution in these cases is to find the common required
> functionality and factor that out to a separate class that is then the
> superclass of two of the existing classes, breaking the circle.
>
> = wibble.py =
> # no dependencies
>
> class Wibble(object):
> pass
> =
>
> = foo.py =
> import wibble
> import bar
>
> class Foo(wibble.Wibble, bar.Bar):
> pass
> =
>
> = baz.py =
> import wibble
>
> class Baz(wibble.Wibble):
> pass
> =
>
> Note that Baz no longer subclasses foo.Foo, and both Foo and Baz get
> the common functionality they share from wibble.Wibble.

I have to think about that for a bit and see if it makes sense to
factor anything out.  Thanks for the idea.  Would that be the best
solution considering the above description?

~Sean
>
> --
>  \ "Buy not what you want, but what you need; what you do not need |
>   `\   is expensive at a penny."  -- Cato, 234-149 BC, Relique |
> _o__)  |
> Ben Finney


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


Re: Circular Class Logic

2007-03-15 Thread half . italian
> Remove the line above
> and add this below:
> def initFoo():
>   import baz
>   Foo.baz = baz.Baz()
> initFoo()

I got it to work, but I had to add a check to see if the class
variable had been set..

def initBaz():
  import Baz
  Foo.baz = Baz.Baz()

class Foo:
  baz = None
  def __init__(self):
if Foo.baz == None:
  Foo.baz = True
  initBaz()

What exactly is being accomplished by having the init function outside
of the class?  If there is no check, wouldn't it just execute every
time an object is instantiated anyway?

> Instead of initFoo, you could use a custom metaclass. Or a class decorator (if
> and when they become available...)

I haven't tried either of those yet.  The names scare me. :)  Sounds
like this might be a good time to explore them.

> The code above is an effective way of doing what you want. But I'd think about
> the actual need of doing such things - are you sure it's a good design?
>

I thought it was a good design, but now I'm not so sure.  I'm
untrained, so often I dont know the right way to do things.  As I
build this into the libraries, I'll keep an eye on how the code is
developing and go from there.Thanks for the help!

~Sean

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


Re: Circular Class Logic

2007-03-15 Thread half . italian
> Just initialize Folder at module level - see below.
> -- Paul
>
> class Disk(Folder):
> def __init__(self,driveLetter):
> super(Disk,self).__init__(driveLetter+":/")

What is going on there?  Is it just explicitly calling the super's
init function?  How is that really different from this:

class Disk(Folder):
  def __init__(self,driveLetter):
Folder.Folder.__init__(self.path) # ???  Being that Folder is the
superclass?

I'd like to be able to use the shared Disk objects in any class that
is a subclass of Data.  Will the above method still make the Disk
objects available in File.py?  Also, what if the classes are in
different modules.

I'll try to experiment with it this afternoon.  I'm using more
information than just the drive letter.  What if the user wants to
find out the unc path to the share given the drive letter, or copy a
file to the local disk that is not a system disk that has the most
available space on it, or wants to mount or unmount a network drive.

pause...

I'm trying to justify why the Folders/Files really need the drive info
beyond just the paths and I'm having a hard time.  I even just tried
to give an example of how it would be used, and couldn't.  It seems to
make sense on a gut level, but maybe it's just as usefull on it's
own.  There's definitely justification for having Disks be a subclass
of Folder, but not necessarily for there to be an instance of it
available within the classes.  All that kind of work will be external
to the class.

I think I'll backtrace and keep it separate.  Thanks for letting me
think it through.

~Sean

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


Re: Circular Class Logic

2007-03-15 Thread half . italian
> > How is that really different from this:
>
> > class Disk(Folder):
> >   def __init__(self,driveLetter):
> > Folder.Folder.__init__(self.path) # ???  Being that Folder is the
> > superclass?
>
> Where did self.path come from?  Even though Folder is the superclass,
> self.path doesn't exist until the Folder.__init__ method gets called.
> This ain't C++ you know.

My bad. I should have said:

class Disk(Folder):
  def __init__(self,driveLetter):
Folder.Folder.__init__(self, driveLetter + ":/")

> Knock yourself out.  I just hacked together these Folder/Disk classes
> by way of a half-baked-but-working example.  My point is that to
> initialize a class level variable on class Foo, all that is needed is
> to assign it in the defining module, that is:
>
> class Foo:
>pass
>
> Foo.fooClassVar = "a class level variable"

> Now any Foo or sub-Foo can access fooClassVar.  The type of
> fooClassVar can be anything you want, whether it is a Foo, subclass of
> Foo or whatever, as long as it has been defined by the time you assign
> fooClassVar.

That was the first thing I tried, but because the libs were importing
each other, etc, it got hung up with wierd "This module doesn't exist"
errors, when it clearly did.

~Sean



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


Re: Prevent Modification of Script?

2007-04-04 Thread half . italian
Just throw out the .py files and let it run on the .pyc's alone.

~Sean

On Apr 4, 8:03 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> ts-dev wrote:
> > The root of my question is verifying the integrity of the application
> > and the scripts being run.
>
> Google "md5sum". Then google "birthday attack".
>
> James


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


  1   2   >