Re: subprocess leaves child living

2007-06-07 Thread reed
On Jun 5, 7:58 am, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
> Hi, When I do a small program like
>
> from subprocess import Popen
> popen = Popen(["ping", "google.com"])
> from time import sleep
> sleep(100)
>
> start it and kill it, the ping process lives on.
> Is there a way to ensure that the ping process is always killed when the
> python process is?
> I can't use atexit, as ping then isn't killed when python is killed "in
> the hard way"



pid = popen.pid
pidfile = open('/usr/local/var/somefile.pid', 'w')
pidfile.write('pid')
pidfile.close()


then you can check if it is still running when your ?program? restarts
and can kill it.

maybe not the perfect answer, but it answers an imperfect question.

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


Re: Tkinter, tkMessagebox and overrideredirect

2007-06-07 Thread marcoberi
On Jun 6, 3:38 pm, "Eric Brunel" <[EMAIL PROTECTED]> wrote:
> My only advice would then be to avoid using the standard functions to
> create dialog boxes, and to create them yourself. For example:
> --
>  from Tkinter import *
[snip]
> app.root.mainloop()
> --
> But even with this, you may run into problems. For example, on my Linux
> box with my window manager, the main window goes behind all other windows
> once the button in the dialog is clicked. So I'd say that if you want to
> bypass the window manager, bypass it for everything and do
> overrideredirect(1) on all the windows you create. But this means that
> you'll have to do everything "manually", especially window stacking.

Besides that, the popup window is yet under the main frame... :-(
Seems to me that dialogWdw.tkraise(self.root) doesn't do its job.
It's like overrideredirect in main window override also tkraise on it.

I can't believe there isn't an easier way to make a kiosk application
without titlebar.
Perhaps to create a normal window bigger than screen with title bar
outside it?
And after how can I ignore titlebar menu command or "x" and "-"
button?
Or is it possible to create a main Toplevel without "x" and "-"?

Thanks.
Ciao.
Marco.


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


Re: howto obtain directory where current (running) py-file is placed?

2007-06-07 Thread Gerard Flanagan
On Jun 7, 8:39 am, dmitrey <[EMAIL PROTECTED]> wrote:
> Hi all,
> I guess this question was asked many times before, but I don't know
> keywords for web search.
>
> Thank you in advance, D.

import os

d1 = os.path.dirname(__file__)
d2 = os.path.dirname(os.__file__)

print d1
print d2

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


Calling Usergroup Organizers (and Wannabees)

2007-06-07 Thread Jeff Rush
We'd like to strengthen and raise the visibility of Python usergroups and
foster the creation of new ones, by sharing the valuable experiences of those
leaders around the community who make it happen.

[1] One step is to make others more aware of what is already happening,
perhaps in their own neighborhood re Python meetings.  I've created a
shared blog and invite organizers of existing groups to send me their
email address to get privs to post to it.

http://python-groups.blogspot.com/

Because these postings will be distributed far and wide, a posting should
be of interest to those who did not attend but are considering doing so,
or that might be instructive to organizers in other cities. An overview of
what was covered in a past meeting, or an announcement with substance on
what an upcoming meeting is going to be about are good postings.  A simple
date and local address, or that the pizza was good last week, is not. ;-)

[2] A second step is to encourage and support new organizers in forming groups
in their area.  There is a strong demand for such meetings, but many are
uncertain how to go about it.  Therefore I've created a new mailing list
on which experienced and new organizers can share tips on getting started,
whether about getting the word out, finding a place to meet or getting
interesting speakers.

http://mail.python.org/mailman/listinfo/group-organizers

Those of us with a history of involvement in a usergroup often forget that
many people have never attended a usergroup meeting, or lack experience in
running one, so let's help strengthen this aspect of Python.  We could use
some videos or photos of group meetings as well, posted to
youtube.com/flickr.com and the link emailed to me for use.

I'd also like to reach out to the existing, successful usergroups and ask them
to spread the word about their efforts by being interviewed by Ron Stephens on
Python411, and/or writing up an article on how your group got started for
Tennessee Leeuwenburg of _The Python Papers_.  Even a simple "what a typical
meeting is like in my area" is helpful.

http://www.awaretek.com/python/index.html
http://pythonpapers.cgpublisher.com/

It would be especially interesting to see how usergroups operate in various
countries around the world, and perhaps help bring together these regions.

In closing, please, for existing usergroups as well as new ones coming online,
update the entry for your group on the roster of Python usergroups.

http://wiki.python.org/moin/LocalUserGroups

Jeff Rush
Advocacy Coordinator
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does Boost.Python participate in cyclic gc?

2007-06-07 Thread Giovanni Bajo
On 05/06/2007 21.32, [EMAIL PROTECTED] wrote:

> We encountered a situation today where it appeared that a
> Boost.Python-provided class didn't participate in Python's cyclic garbage
> collection.  The wrapped C++ instance held a reference to a method in the
> Python object which referenced the Boostified C++ instance, e.g.:

Those situations get more and more common as you keep wrapping your code. To 
the best of my knowledge, SIP is the only one which does the right thing here.
-- 
Giovanni Bajo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MoinMoin configuration

2007-06-07 Thread Hendrik van Rooyen
 "Eric S. Johansson" <[EMAIL PROTECTED]> wrote:

> (currently beating my head against flash memory and grub problems).  So if you
> come up with a solution, feel free to e-mail me directly or if you have any
> other questions, also, feel free to send me mail.  Might not know the answer
but
> at least we can commiserate.  :-)

Misery shared is misery halved...

:-)

- Hendrik

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


Help a C++ escapee!

2007-06-07 Thread Simon Pickles
Hi,

Can someone help me leave the murky c++ world and enter shiny pythonland?

I have a problem with importing and global variables, here's my code:


##server.py

#socket connections
from socketManager import*

network = CNetworkManager()
network.Listen()

--
##socketManager.py

from time import sleep
from socket import*

import threading


class CNetworkManager():
def __init__(self):
self.hostName = ""
self.portNumber = 15500
self.buffer = 500
self.serverAddress = ( self.hostName, self.portNumber )
self.maxClients = 2
## previous stuff to send to new client
self.serverData = []

self.serverSocket = socket ( AF_INET, SOCK_STREAM )
self.serverSocket.bind ( self.serverAddress )
print( "Socket started " )
self.serverSocket.listen ( self.maxClients )
print( "Server is waiting for a connection" )

def Listen(self):
self.threadArray =[]
self.ch = 0
while self.ch < self.maxClients:
#Create a thread listening to each socket
self.newThreadObject = CServerThread()
self.newThreadObject.start()
self. threadArray.append(self.newThreadObject)
self.ch=self.ch+1



class CServerThread(threading.Thread):
def run(self):
while (1):
self.clientSocket, self.clientAddress = network.accept()
print("New Client:", self.clientAddress)
if network.serverData:
for i in range(len(network.serverData)):
clientSocket.send(str(network.serverData[i]))
sleep(0.01)
else:
clientSocket.send("You are logged in")
print("Entering loop for client ", clientAddress )
while 1:
clientData = clientSocket.recv(Buffer)
if not clientData:
print( clientAddress + " has closed the connection" )
break
print( "%s says %s" % (clientAddress, clientData))
clientData = clientData + "~~"
network.serverData.append(clientData)
for i in range(len(network.serverData)):
clientSocket.send(str(network.serverData[i]))
sleep(0.01)
print("Ready to receive more data")

clientData.close()
break
network.serverSocket.close()
--

When run, I come unstuck here:

self.clientSocket, self.clientAddress = network.accept()

I get a nameError on 'network', yet it is one in the global namespace, 
defined in server.py before CServerThread.Listen() is called.

In c++, I understood how to declare variables, here I have a problem. Its 
like I need an extern statement from c++.

Can anyone clarify this for me?

Many thanks

Simon

_
Play your part in making history - Email Britain! 
http://www.emailbritain.co.uk/

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


RE: MySQL InterfaceError

2007-06-07 Thread Joe
> Try passing the cursor and not the connection -

Unfortunately this provided the same InterfaceError.  It was one of the
first options we had tried in correcting the situation.  Is there any way to
check on the status of a database connection (like an isOpen() method)?  It
appeared as though the connection (and cursor) would sporadically close upon
passing between modules.

Thanks!

Jough

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


Multithreaded PyGtk application problems

2007-06-07 Thread lost script

I needed a thread which will run in background , collect some information
from other hosts and save info in database periodically.
While gtk thread will show the collected information from database.
It works but gtk response is too slow. Can anyone help  or give any link of
such a sample application (multithreaded pygtk)?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Basic Auth for simple web server

2007-06-07 Thread Marco Aloisio
Thanks

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


Integer division

2007-06-07 Thread [EMAIL PROTECTED]
Hello all,
 I have two integers and I want to divide one by another, and want to
get an integer result which is the higher side whenever the result is
a fraction.
 3/2 => 1 # Usual behavior
 some_func(3, 2) => 2 # Wanted

Any easier solution other than int(math.ceil(float(3)/2))

-
Suresh

-- 
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


Verify server certificate in HTTPS transaction

2007-06-07 Thread Hamish Moffatt
Hi,
I'm fetching some files over HTTPS from Python and I want to verify the 
server certificate. (Not just the name etc provided in certificate.)

How can I get access to this information?

urllib2 doesn't seem to provide it. Even a raw SSL socket only appears 
to provide access to the CN, OU etc in string form (not the raw 
certificate).

I tried pycurl, which allows you to setopt(pycurl.SSL_VERIFYPEER) and 
VERIFYHOST, but the getinfo(pycurl.SSL_VERIFYRESULT) call always returns 
0. Perhaps it's unimplememented?

I couldn't get the M2Crypto API documentation to generate; perhaps it 
allows it.

TLS Lite on to of M2Crypto? Something else again?


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


Re: Integer division

2007-06-07 Thread Hamish Moffatt
[EMAIL PROTECTED] wrote:
> Hello all,
>  I have two integers and I want to divide one by another, and want to
> get an integer result which is the higher side whenever the result is
> a fraction.
>  3/2 => 1 # Usual behavior
>  some_func(3, 2) => 2 # Wanted
> 
> Any easier solution other than int(math.ceil(float(3)/2))

The normal solution is to add (divisor-1) to the dividend before division.

Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct.

But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct.



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


Re: Help a C++ escapee!

2007-06-07 Thread Ant
Hi Simon,

> When run, I come unstuck here:
>
> self.clientSocket, self.clientAddress = network.accept()
>
> I get a nameError on 'network', yet it is one in the global namespace,
> defined in server.py before CServerThread.Listen() is called.

You have imported everything from socketManager in server.py, but
socketManager knows nothing about any globals defined in the server
module! You'd need to import it in socketManager.py:

from server import network

However this may not work, since you have circular dependencies in
your code - server requires socketManager and vice versa. Even if this
does work it is bad practice, and is an indication that your classes
are in the wrong modules, or that your classes need refactoring
somewhat.

A simple solution would be to pass an instance of the CNetworkManager
into CServerThread. i.e.

...
def Listen(self):
self.threadArray =[]
self.ch = 0
while self.ch < self.maxClients:
#Create a thread listening to each socket
self.newThreadObject = CServerThread(self)
self.newThreadObject.start()
self. threadArray.append(self.newThreadObject)
self.ch=self.ch+1
class CServerThread(threading.Thread):
def __init__(self, network):
self.network = network

def run(self):
while (1):
self.clientSocket, self.clientAddress =
self.network.accept()

...

HTH.

--
Ant...

http://antroy.blogspot.com/





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


Re: Help a C++ escapee!

2007-06-07 Thread Paul Melis
Hello,

Simon Pickles wrote:
> Can someone help me leave the murky c++ world and enter shiny pythonland?

Welcome!

> I have a problem with importing and global variables, here's my code:
> 
> [...]
 >
> When run, I come unstuck here:
> 
>self.clientSocket, self.clientAddress = network.accept()
> 
> I get a nameError on 'network', yet it is one in the global namespace, 
> defined in server.py before CServerThread.Listen() is called.

That won't work (as you found out :)). You need to make 'network' 
available within socketManager.py. Each module on its own has a 
namespace, there isn't such a thing as a global namespace that is 
accessible from all modules, like you are used to in C or C++.

So when you access the variable 'network' in module socketManager it is 
looked up in that module's namespace. When you read through 
socketManager.py (without looking at any other code) you will see that 
'network' isn't being defined anywhere. I would solve it like this:

Pass it as a parameter to CNetworkManager's and CServerThread's 
constructor and store it as an instance variable, i.e. for CNetworkManager:

class CNetworkManager:
def __init__(self, network):
self.network = network
...

and then later pass it again to the thread you're creating.

Another way to have something a bit more like a global namespace would 
be to create a new module, say we name it globals.py.

-
# globals.py

# initially, no network set
network = None
-

Each module that needs access to globals would then import the globals 
module and access its variables. So, server.py would do

import globals
globals.network = CNetworkManager()
globals.network.Listen()

and socketManager.py would do

import globals

  ...
  self.clientSocket, self.clientAddress = globals.network.accept()

(You could also selectively import the network variable of course with 
"from globals import network").

Hope this helps,
Paul


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


Re: Help a C++ escapee!

2007-06-07 Thread Bjoern Schliessmann
Simon Pickles wrote:

> from socket import *

Bad idea, can make conflicts in namespace.
 
> import threading

There's absolutely no need to use threads for a server that accepts
multiple connections :)

> class CNetworkManager():

Note that you create an "old style" class. For new style classes,
inherit from "object".

> print("New Client:", self.clientAddress)
> if network.serverData:
> for i in range(len(network.serverData)):
> clientSocket.send(str(network.serverData[i]))
> sleep(0.01)

Using for like this is in most cases ugly and not needed. Better
would be to use here

for data in network.serverdata:
clientSocket.send(str(data))

It does the same. Remember, C++ needs an index in for, Python only
needs an iterable (e.g. a list or string) as for argument and does
the rest by itself.

BTW, what's the sleep for?

> while 1:
> clientData = clientSocket.recv(Buffer)
> if not clientData:
> print( clientAddress + " has closed the
> connection" ) 

What exactly is the closing condition here? In my understanding, you
should always receive something, at least a "\n" or "\r\n".

Also note that comments and docstrings are cool, and parentheses around
the print statements' parameters are superfluous.

> When run, I come unstuck here:
> 
> self.clientSocket, self.clientAddress =
> network.accept()
> 
> I get a nameError on 'network', yet it is one in the global
> namespace, 

No, it's in global module namespace, not global namespace. Outside
of the module where it's defined, no one knows it, except you import
it explicitly there.

> In c++, I understood how to declare variables, here I have a
> problem. Its like I need an extern statement from c++.

Better 

* use import or
* pass "network" using the constructor of the class using it or
* put it all in the same file.

Hope that helps.

BTW, using those low level functions you make yourself more hassle
than you really need. Have a look at this, it's mainly your server
programmed using Twisted framework[1]. I think that's much easier,
you can concentrate on your program instead of having to care about
connection and data receiving management.

--
#!/usr/bin/env python

from twisted.internet import protocol, reactor
from twisted.protocols import basic

class CNetwork(basic.LineReceiver):
def connectionMade(self):
print "New Client:", self.transport.getPeer().host
self.send = lambda x: self.transport.write(x+"\r\n")
if self.factory.server_data:
self.send("\r\n".join(self.factory.server_data))
else:
self.send("You are logged in")
print "Entering loop for client", self.transport.getPeer().host

def connectionLost(self, reason):
print self.transport.getPeer().host, "has closed the connection"

def dataReceived(self, data):
data = data.strip()
if not data:
self.transport.loseConnection()
return
print "%s says %r" % (self.transport.getPeer().host,
  data)
self.factory.server_data.append(data + "~~")
print "Ready to receive more data"

class CNetworkFactory(protocol.Factory):
protocol = CNetwork
def __init__(self, max_clients):
self.max_clients = max_clients
self.connected_clients = 0
self.server_data = []

def startFactory(self):
print "Factory started -- server is waiting for a connection"

def main():
reactor.listenTCP(15500, CNetworkFactory(max_clients = 2))
reactor.run()

if __name__ == "__main__":
main()
--

You could also run this here by creating a server.py like yours,
importing only twisted.internet.reactor and the factory class and
passing the latter to reactor.listenTCP there.

Regards,


Björn

[1] http://twistedmatrix.com/projects/core/documentation/howto/index.html

-- 
BOFH excuse #20:

divide-by-zero error

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


Re: Integer division

2007-06-07 Thread [EMAIL PROTECTED]
On Jun 7, 2:15 pm, Hamish Moffatt <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello all,
> >  I have two integers and I want to divide one by another, and want to
> > get an integer result which is the higher side whenever the result is
> > a fraction.
> >  3/2 => 1 # Usual behavior
> >  some_func(3, 2) => 2 # Wanted
>
> > Any easier solution other than int(math.ceil(float(3)/2))
>
> The normal solution is to add (divisor-1) to the dividend before division.
>
> Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct.
>
> But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct.
>
> Hamish

What about this?

>>> def div_ceil(a, b):
... if a%b:
... return ((a/b)+1)
... else:
... return (a/b)
...
>>> div_ceil(3,2)
2
>>> div_ceil(-3,2)
-1
>>> -3%2
1
>>> -(3%2)
-1
>>> div_ceil(-5,2)
-2
>>> div_ceil(5,2)
3

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


Re: Tkinter, tkMessagebox and overrideredirect

2007-06-07 Thread Eric Brunel
On Thu, 07 Jun 2007 09:04:24 +0200, <[EMAIL PROTECTED]> wrote:
[snip]
> I can't believe there isn't an easier way to make a kiosk application
> without titlebar.

That's not the problem: there *is* an easy way, and you found it:  
overrideredirect(1). But now you're trying to mix windows ignored by the  
window manager - as you've told it to - and windows that *are* managed by  
the window manager. This is where the problem is.

> Perhaps to create a normal window bigger than screen with title bar
> outside it?

This won't work on some platforms and/or with some window managers... And  
there's no portable way to do that, as sometimes, the dimensions you give  
for the window includes the window decorations, and sometimes they don't.

> And after how can I ignore titlebar menu command or "x" and "-"
> button?

For the 'X' button, it's quite simple:  
myToplevel.protocol('WM_DELETE_WINDOW', lambda: None)

For the '-' button, I don't know any way.

> Or is it possible to create a main Toplevel without "x" and "-"?

Apart from overrideredirect(1), I don't think there's any.


BTW, what are you trying to do here? Will your application run on a  
"normal" desktop computer? Or will it run on special devices such as  
vending machines or similar? If in the first case, my advice would be to  
give up this design (which many people hate, BTW) and use normal windows.  
You'll have far less trouble and will probably make your users happier. If  
in the second case, you shouldn't rely on an existing window manager, and  
try to design your GUI so that doing things "manually" will be easier. For  
example, instead of displaying a dialog for a message, maybe you should  
just reserve a screen zone to display the message, optionally displaying  
it in a special color or making it blink so that the user can't miss it.  
You may also consider using the "place" layout method to display things at  
random coordinates in your application window. For example:


 from Tkinter import *

class App:
 def __init__(self):
 self.root = Tk()
 self.root.overrideredirect(1)
 frm = Frame(self.root, width=320, height=200,
borderwidth=5, relief=RAISED)
 frm.pack_propagate(0)
 frm.pack()
 Button(frm, text="Quit", command=self.root.quit).pack(pady=20)
 Button(frm, text="Hello", command=self.hello).pack(pady=20)

 def hello(self):
 self.dialogWdw = Frame(self.root, borderwidth=2, relief=RAISED)
 Label(self.dialogWdw, text='Hello!').pack(side=TOP, padx=20,  
pady=4)
 Button(self.dialogWdw, text='OK',  
command=self.destroyDialog).pack(side=TOP, padx=20, pady=4)
 self.dialogWdw.place(x=170, y=100, anchor='center')

 def destroyDialog(self):
 self.dialogWdw.place_forget()
 self.dialogWdw.destroy()


app = App()
app.root.mainloop()


HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determinant of Large Matrix

2007-06-07 Thread Bjoern Schliessmann
James Stroud wrote:

> If I run it again on 10 (or 1000) the set is basically homogenous
> but now of different values (terribly confusing):
> 
> set([12048175104.1, 12048175104.15, 12048175104.46,
> 12048175103.94, 12048175104.23, 12048175103.81,
> 12048175103.98, 12048175103.9])

As you seem to have overread it: Note that Python only prints those
numbers with full "bogus" precision since you let it display them
using repr() (it's used in lists by default for display). If you
use str() explicitly, Python applies rounding:
 
>>> A
[12048175104.1, 12048175104.15, 12048175104.46,
12048175103.94, 12048175104.23, 12048175103.81,
12048175103.94, 12048175104.23, 12048175103.81,
12048175103.98, 12048175103.9]
>>> [repr(i) for i in A]
['12048175104.1', '12048175104.15', '12048175104.46',
'12048175103.94', '12048175104.23', '12048175103.81',
'12048175103.94', '12048175104.23', '12048175103.81',
'12048175103.98', '12048175103.9']
>>> [str(i) for i in A]
['12048175104.0', '12048175104.0', '12048175104.0', '12048175104.0',
'12048175104.0', '12048175104.0', '12048175104.0', '12048175104.0',
'12048175104.0', '12048175104.0', '12048175104.0']
>>> 

Regards,


Björn

-- 
BOFH excuse #83:

Support staff hung over, send aspirin and come back LATER.

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


Where can I suggest an enchantment for Python Zip lib?

2007-06-07 Thread durumdara
Hi!

Where can I ask it?

I want to ask that developers change the Python's Zip lib in the next 
versions.
The Zip lib not have a callback procedure. When I zip something, I don't 
know, what is the actual position of the processing, and how many bytes 
remaining.
It is simply rewriteable, but when I get new Python, it is forget this 
thing again...

So some callback needed for it, if possible. With this I can abort 
processing and I can show the actual state when I processing a large file.

See this thread:
http://groups.google.com.kh/group/comp.lang.python/browse_thread/thread/c6069d12273025bf/18b9b1c286d9af7b?lnk=st&q=python+zip+callback&rnum=1#18b9b1c286d9af7b

Thanks for your help:
dd


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


Re: “On Your Desktop”: the celebr ity posting editorial blog

2007-06-07 Thread James Stroud
Steve Holden wrote:
> The first post comes from Ian Bicking:
> 
> http://onyourdesktop.blogspot.com/
> 
"Linux was a remote possibility: just why is it so bad as a laptop OS?"

I'm a diehard os x man myself, but I spent about 1.5 days setting up 
ubuntu feisty on an Acer Travel Mate TM2480-2779 ($459 after rebate from 
newegg). Set up wireless (got WEP going but WPA was beyond my patience), 
full resolution from the monitor, and the soundcard going 100%. None of 
this was straightforward but it was all plenty doable with sufficient 
diligence. You will have to compile a kernel module or 2. It makes for a 
nice little linux box once you get everything configured. The acer 
hardware is pretty respectable, especially for the price. I'm not quite 
ready to trade in my 15" Core2Duo MBP, though, as there is no substitute 
for tasty apple hardware.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginning Python

2007-06-07 Thread janislaw
On Jun 5, 4:29 pm, abhiee <[EMAIL PROTECTED]> wrote:
> Hello , I have just begun learning python...and I'm loving it...Just
> wanted to ask you that how much time would it take me to learn python
> completely and which languages should i learn alongwith python to be a
> good professional programmer?...Now i only know C
> thanx in advance!

Then Lisp is a must-know to you.

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


Re: Determinant of Large Matrix

2007-06-07 Thread Mark Westwood
Hi James

Mathematica says that the determinant of the integer version of this
matrix is 2774532096, which is another vote for the answer you have.

Mathematica says that the determinant of the 24-digit real version of
your matrix is 2.774532096*10^9, which looks very similar to me.

I'd go with Numpy.

Regards

Mark Westwood


PS 13x13 isn't a large matrix !


On Jun 6, 12:10 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> I'm using numpy to calculate determinants of matrices that look like
> this (13x13):
>
> [[ 0.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
>   [ 1.  0.  1.  4.  1.  9.  4.  4.  1.  1.  4.  9.  4.  9.]
>   [ 1.  1.  0.  1.  4.  4.  9.  9.  4.  4.  1.  4.  1.  4.]
>   [ 1.  4.  1.  0.  9.  1.  4.  4.  9.  1.  4.  1.  4.  1.]
>   [ 1.  1.  4.  9.  0.  4.  4.  4.  1.  4.  1.  9.  4.  9.]
>   [ 1.  9.  4.  1.  4.  0.  4.  4.  9.  4.  1.  1.  4.  1.]
>   [ 1.  4.  9.  4.  4.  4.  0.  1.  1.  1.  9.  1.  9.  4.]
>   [ 1.  4.  9.  4.  4.  4.  1.  0.  4.  1.  9.  4.  4.  1.]
>   [ 1.  1.  4.  9.  1.  9.  1.  4.  0.  4.  4.  4.  4.  9.]
>   [ 1.  1.  4.  1.  4.  4.  1.  1.  4.  0.  9.  4.  9.  4.]
>   [ 1.  4.  1.  4.  1.  1.  9.  9.  4.  9.  0.  4.  1.  4.]
>   [ 1.  9.  4.  1.  9.  1.  1.  4.  4.  4.  4.  0.  4.  1.]
>   [ 1.  4.  1.  4.  4.  4.  9.  4.  4.  9.  1.  4.  0.  1.]
>   [ 1.  9.  4.  1.  9.  1.  4.  1.  9.  4.  4.  1.  1.  0.]]
>
> For this matrix, I'm getting this with numpy:
>
>   2774532095.971
>
> But I have a feeling I'm exceeding the capacity of floats here. Does
> anyone have an idea for how to treat this? Is it absurd to think I could
> get a determinant of this matrix? Is there a python package that could
> help me?
>
> Many thanks for any answers.
>
> James


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


get a list from a string

2007-06-07 Thread simon kagwe
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

-- 
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: get a list from a string

2007-06-07 Thread simon kagwe
> exec("distances = [[1,1,1,1],[2,2,2,2]]")
Wow! So simple!

Thanks a lot. :-)




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


Re: Tkinter, tkMessagebox and overrideredirect

2007-06-07 Thread marcoberi
On Jun 7, 12:01 pm, "Eric Brunel" <[EMAIL PROTECTED]> wrote:
> BTW, what are you trying to do here? Will your application run on a
> "normal" desktop computer? Or will it run on special devices such as
> vending machines or similar?

You got it: it's a special device.

> in the second case, you shouldn't rely on an existing window manager, and
> try to design your GUI so that doing things "manually" will be easier. For
> example, instead of displaying a dialog for a message, maybe you should
> just reserve a screen zone to display the message, optionally displaying
> it in a special color or making it blink so that the user can't miss it.
> You may also consider using the "place" layout method to display things at
> random coordinates in your application window. For example:

You are right and I think it's not a big deal for simple popup
messages.
But when I need tkFileDialog.askdirectory I think things get harder.
I would prefer not have to reimplement the whole stuff from scratch...

Ciao.
Marco.
P.S. BTW I already owe you a pizza for your help. Do you think you can
be at http://www.pycon.it this weekend? :-)

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


Why can not catch the inner exception

2007-06-07 Thread 人言落日是天涯,望极天涯不见家
Please see the follow code,  I can not catch the exception " IOError"
raised from shutil.copyfile() , why?
try:
if (DEST_TYPE & TYPE_FTP):
fn = oname
ftpc.UploadFile(f, fn)
else:
fn = os.path.join(dst, oname)
shutil.copyfile(f, fn)

 other code

except [IOError, FtpcException],why:
num = 0
print >>sys.stderr, "can not copy '%s' to '%s':
%s"%(f, fn, why)
ERR_NUM += 1

I must do like this:
try:
if (DEST_TYPE & TYPE_FTP):
fn = oname
ftpc.UploadFile(f, fn)
else:
fn = os.path.join(dst, oname)
try:
 shutil.copyfile(f, fn)
except IOError:
   

 other code

except [IOError, FtpcException],why:
num = 0
print >>sys.stderr, "can not copy '%s' to '%s':
%s"%(f, fn, why)
ERR_NUM += 1

Thanks!

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

Re: howto obtain directory where current (running) py-file is placed?

2007-06-07 Thread dmitrey
On Jun 7, 10:18 am, Gerard Flanagan <[EMAIL PROTECTED]> wrote:
> On Jun 7, 8:39 am, dmitrey <[EMAIL PROTECTED]> wrote:
Thank you.
And what is the simplest way (without split/join, if exist) to obtain
name of directory parent to directory my_directory_name?

Thx, D.

>
> > Hi all,
> > I guess this question was asked many times before, but I don't know
> > keywords for web search.
>
> > Thank you in advance, D.
>
> import os
>
> d1 = os.path.dirname(__file__)
> d2 = os.path.dirname(os.__file__)
>
> print d1
> print d2


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


recursion error using setattr and getattr

2007-06-07 Thread Nathan Harmston
Hi,

I m trying to implement an object which contains lazy" variables. My
idea is to alter the getattr and the setattr methods. However I keep
on getting a recursion error.

My idea is that the lazy variable can be stored in a variety of
places, Database, PyTables etc. The lazy variable is a large variable
and so I dont want to hold it in memory all of the time, I d rather
just get it when needed and then store it for future work. Most of the
work will be done using var1 and var2

So ..

class LazyBase(object):
self.var1 = 0
self.var2 = None
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __setattr__(self, attr, k):
if attr == "var1":  
if self.var1 != k
self.var1 = k
if self.lazy != None
self.lazy = None
elif attr == "var2" :
if self.var2 != k
self.var2 = k
if self.lazy != None
self.lazy = None
else:
raise Exception("Attribute")


class SQLLazy(LazyBase):
def __init__(self, name, table="test_table"):
self.table = table
LazyBase.__init__(name)
self.lazy = None
def __getattr__(self, attr):
if attr == "lazy":
if self.lazy == None: # problem line I think
print "Hit Database"
# use sqlalchemy to get the variable
# set self.lazy = lazy
return self.lazy
else:
return self.lazy
else:
try:
return Lazy.__getattr__(attr)
except:
raise Exception("Attribute Exception")
def __setattr__(self, attr, k):
if attr == "lazy"
raise Exception("Cannot alter lazy")
else:
try:
Lazy.__setattr__(attr, k)
except:
raise Exception("Attribute Exception")

if __name__=='__main__':
spam = SQLLazy("Test")
spam.var2 = 10
print spam.lazy
print spam.lazy
spam.var2 = 5
print spam.lazy

I m expecting the output:
Hit Database
Lazy Variable
Lazy Variable
Hit Database
Lazy Variable   

However I just get recursion errors. Does anyone have any ideas how I
can implement this sort of thing through my current method, or is
there a better way to accomplish this.

THanks

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


Re: Integer division

2007-06-07 Thread Sion Arrowsmith
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 3/2 => 1 # Usual behavior
> some_func(3, 2) => 2 # Wanted

def some_func(a, b):
return -(-a/b)

And people complain about Python's behaviour regarding division of
negative integers.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: recursion error using setattr and getattr

2007-06-07 Thread Simon Brunning
On 6/7/07, Nathan Harmston <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I m trying to implement an object which contains lazy" variables. My
> idea is to alter the getattr and the setattr methods. However I keep
> on getting a recursion error.

Simplifying radically, you are doing:

def __setattr__(self, attr, k):
if attr == "var1":
self.var1 = k

The last line here sets the var1 attribute, and that goes through your
__setattr__() method again; henct the recursion error. You need to
bypass the  __setattr__() method with something like:

self.__dict__['var1'] = k

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get a list from a string

2007-06-07 Thread Dustan
On Jun 7, 6:06 am, simon kagwe <[EMAIL PROTECTED]> wrote:
> > exec("distances = [[1,1,1,1],[2,2,2,2]]")

To be clear, exec is *not* a function; it's a statement. That means it
can't be used in lambda functions, for example.

> Wow! So simple!

but dodgy, as it'll execute any python code.

> Thanks a lot. :-)

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


Re: get a list from a string

2007-06-07 Thread Josef Dalcolmo

simon kagwe 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?

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

- Josef

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


How to wrap a Japanese text in Python

2007-06-07 Thread prashantkisanpatil
Hi All,

I am trying to wrap a japanese text in Python, by the following code.

if len(message) > 54:
   message = message.decode("UTF8")
   strlist = textwrap.wrap(message,54)

After this I am wirting it to you a CAD Software window. While
displaying in this window some Japanese characters at the end of the
line & some at the begining of the line are not displayed at all.
Meaning the text wrapping is not happening correctly.

Can any body please help me out in resolving this problem.

Thanks in advance.

Regards,
Prashant

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


RE: creating lists based on parsed items

2007-06-07 Thread Jason White
Sorry ... one minor detail lacking. I'm saddled with Python 2.3.4

Jason


-Original Message-
From: [EMAIL PROTECTED] on behalf of Basilisk96
Sent: Wed 6/6/2007 6:49 PM
To: python-list@python.org
Subject: Re: creating lists based on parsed items
 
> If you are using Python 2.5, use a defaultdict instead, the very first
> example looks like what you want.
> 
>
> --
> Gabriel Genellina

Uh-oh..
I am using Python 2.5 on WinXP, but when I tried the examples in the
manual, I got a "NameError: name 'defaultdict' is not defined".  What
am I missing in my Python installation?

-Basilisk96

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

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

Re: howto obtain directory where current (running) py-file is placed?

2007-06-07 Thread Gerard Flanagan
On Jun 7, 1:19 pm, dmitrey <[EMAIL PROTECTED]> wrote:
> On Jun 7, 10:18 am, Gerard Flanagan <[EMAIL PROTECTED]> wrote:> On Jun 7, 
> 8:39 am, dmitrey <[EMAIL PROTECTED]> wrote:
>
> Thank you.
> And what is the simplest way (without split/join, if exist) to obtain
> name of directory parent to directory my_directory_name?
>
> Thx, D.
>

>>> os.path.join(os.pardir, os.path.dirname('/a/b/c/d/e/f.log'))
'/a/b/c/d/e'
>>> os.path.join(os.pardir, os.path.dirname(_))
'/a/b/c/d'
>>> os.path.join(os.pardir, os.path.dirname(_))
'/a/b/c'
>>> os.path.join(os.pardir, os.path.dirname(_))
'/a/b'
>>> os.path.join(os.pardir, os.path.dirname(_))
'/a'
>>> os.path.join(os.pardir, os.path.dirname(_))
'/'
>>> os.path.join(os.pardir, os.path.dirname(_))
'/'

(When using the interactive interpreter, an underscore '_' means 'the
previous result')

HTH

Gerard

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


Re: "On Your Desktop": the celebrity posting editorial blog

2007-06-07 Thread Paul Boddie
On 7 Jun, 12:09, James Stroud <[EMAIL PROTECTED]> wrote:
> Steve Holden wrote:
> > The first post comes from Ian Bicking:
>
> >http://onyourdesktop.blogspot.com/
>
> "Linux was a remote possibility: just why is it so bad as a laptop OS?"

There are no mysteries about Linux vs. laptop hardware, although
lightly-informed pontification on the subject fuels sites like OSNews.
With secretive hardware vendors unwilling to tell people how their
devices work, yet unwilling to write Linux drivers themselves, it's up
to the community to make educated guesses about things like power
management and the various mobile chipsets.

Anyway, apart from the Python "celebrity" aspect, what's the Python
connection?

Paul

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


Re: get a list from a string

2007-06-07 Thread Steven D'Aprano
On Thu, 07 Jun 2007 11:06:54 +, simon kagwe wrote:

>> exec("distances = [[1,1,1,1],[2,2,2,2]]")
> Wow! So simple!
> 
> Thanks a lot. :-)

Yes, and when you embed this in your web-application, using data gathered
from a web-form, the black-hat hackers will thank you for the security
hole too.

Surely a much better solution would be NOT to start with a string like 
"distances = [[1,1,1,1],[2,2,2,2]]" in the first place? Where does that
string come from? If it comes from the user, at run-time, using exec is a
MAJOR security hole. If it comes from the source code, then WHY???

I wish exec and eval were hidden away in a module so they were harder (but
not impossible) to get to. Because I'm paranoid, I wish importing that
module would print an warning saying "Are you MAD??? Don't do this!!!". I
wish even more that Python would come with a built-in "make a list from a
list representation" function, but that at least is fairly easy to create:
you can modify 




Here is a discussion about just how hard (that is, probably impossible) it
is to make eval safe:

http://effbot.org/zone/librarybook-core-eval.htm




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


Help with PAM and ctypes

2007-06-07 Thread Chris AtLee
Sorry for the repeat post...I'm not sure if my first post (on May
30th) went through or
not.

I've been trying to write a PAM module using ctypes.  In the
conversation
function (my_conv in the script below), you're passed in a
pam_response**
pointer.  You're supposed to allocate an array of pam_response's and
set
the pointer's value to the new array.  Then you fill in the array with
appropriate data.

I can't seem to get it working in python...The authenticate function
always
returns PAM_AUTHTOK_RECOVER_ERR (21), which I think means the response
doesn't make any sense.

I've tried saving the response array outside of my_conv to make sure
it
doesn't get garbage collected, but that doesn't seem to help.

Any pointers would be appreciated!

Cheers,
Chris

from ctypes import *

libpam = CDLL("libpam.so")

class pam_handle(Structure):
_fields_ = [
("handle", c_void_p)
]

def __init__(self):
self.handle = 0

class pam_message(Structure):
_fields_ = [
("msg_style", c_int),
("msg", c_char_p),
]

def __repr__(self):
return "" % (self.msg_style, self.msg)

class pam_response(Structure):
_fields_ = [
("resp", c_char_p),
("resp_retcode", c_int),
]

def __repr__(self):
return "" % (self.resp_retcode,
self.resp)

conv_func = CFUNCTYPE(c_int,
c_int, POINTER(POINTER(pam_message)),
POINTER(POINTER(pam_response)), c_void_p)

class pam_conv(Structure):
_fields_ = [
("conv", conv_func),
("appdata_ptr", c_void_p)
]

pam_start = libpam.pam_start
pam_start.restype = c_int
pam_start.argtypes = [c_char_p, c_char_p, POINTER(pam_conv),
POINTER(pam_handle)]

pam_authenticate = libpam.pam_authenticate
pam_authenticate.restype = c_int
pam_authenticate.argtypes = [pam_handle, c_int]

if __name__ == "__main__":
import getpass, os, sys
@conv_func
def my_conv(nMessages, messages, pResponse, appData):
# Create an array of nMessages response objects
# Does r get GC'ed after we're all done?
r = (pam_response * nMessages)()
pResponse.contents = cast(r, POINTER(pam_response))
for i in range(nMessages):
if messages[i].contents.msg == "Password: ":
p = getpass.getpass()
pResponse.contents[0].resp_retcode = 0
pResponse.contents[0].resp = p
return 0

handle = pam_handle()
c = pam_conv(my_conv, 0)
retval = pam_start("login", os.getlogin(), pointer(c),
pointer(handle))

if retval != 0:
print "Couldn't start pam session"
sys.exit(-1)

retval = pam_authenticate(handle, 0)
if retval == 21:
print "Authentication information cannot be recovered"
sys.exit(-1)

print retval

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


Re: get a list from a string

2007-06-07 Thread Steven D'Aprano
Ah, sorry, pre-mature sending. Stupid keyboard accelerators :(

To finish the sentence I was trying to write:

On Thu, 07 Jun 2007 22:39:41 +1000, Steven D'Aprano wrote:

> I wish even more that Python would come with a built-in "make a list from a
> list representation" function, but that at least is fairly easy to create:
> you can modify 

... Fredrik Lundh's safe-eval function:

http://online.effbot.org/2005_11_01_archive.htm




-- 
Steven.

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


Bragging about Python

2007-06-07 Thread [EMAIL PROTECTED]
Is there a resource somewhere on the net that can be used to quickly
and effectively show Python's strengths to non-Python programmers?
Small examples that will make them go "Wow, that _is_ neat"?

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


Re: Bragging about Python

2007-06-07 Thread Steve Howell

--- "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:

> Is there a resource somewhere on the net that can be
> used to quickly
> and effectively show Python's strengths to
> non-Python programmers?
> Small examples that will make them go "Wow, that
> _is_ neat"?
> 

15 small programs here:

http://wiki.python.org/moin/SimplePrograms




   

Need a vacation? Get great deals
to amazing places on Yahoo! Travel.
http://travel.yahoo.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Unable to start IDLE

2007-06-07 Thread Kishore D

Hi,
I am facing a problem in starting IDLE. The hourglass appears for a
while and then goes off. When i tried opening it after switching of the
firewall, it still din help. If some other program is accessing the port can
anyone tell me how to assign the port to python. Thanks .
-- 
http://mail.python.org/mailman/listinfo/python-list

RE: creating lists based on parsed items

2007-06-07 Thread Jason White
Thanks ... Seems just like perl's list-in-a-hash (I've read some of the 
archives and no, I'm not seeking to incite a perl-vs-python flame war). I 
thought of doing this initially (and would have done via Perl), but didn't 
quite have a grip on associative arrays in python yet. Thanks for the input.

I've since stepped back and resolved the issue in a different way. The 
'buckets' were place holders to go into separate files. It was easier to just 
open the files in append mode and use the bucket name var to sort them straight 
into files. Was sort of a 'coulda had a V-8' moment. Wrapped it in a shell 
script that makes sure the files are removed at the outset.

Many thanks,

Jason


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Gabriel Genellina
Sent: Wednesday, June 06, 2007 5:38 PM
To: python-list@python.org
Subject: Re: creating lists based on parsed items

En Wed, 06 Jun 2007 13:24:54 -0300, Jason White <[EMAIL PROTECTED]>
escribió:

> I am trying to do what (I think) should be fairly straightforward. I 
> have a list of items that i want to sort into buckets. in item 1 of 
> each line is the object I want to sort and in item 2 is the name of 
> the bucket. I am making it dynamic however (so I don't know the bucket 
> names in advance).

Forget about eval!
Use a dictionary: keys are bucket names, values a list containing all 
associated items. You will find the setdefault method very useful.

d = {}
for each item, do: d.setdefault(bucket, []).append(item)

If you are using Python 2.5, use a defaultdict instead, the very first example 
looks like what you want.


--
Gabriel Genellina

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


subprocess call acts differently than command line call?

2007-06-07 Thread Jim
Hello,

I need a program that will traverse a directory tree to ensure that
there
are unix-style line endings on every file in that tree that is a text
file.
To tell text files from others I want to use the unix "file" command
(Python's "mimetypes" is not so good for me).  But I am stuck on
something about getting that output, and I'd greatly appreciate any
pointers.

Both the command line "file" and the python libmagic binding give the
same behavior, but I'll illustrate with "file".  It sometimes acts
differently when run from the command line than when run using
the subprocess module (with the same user).  For example, it
sometimes
gives output when run from the command line but no output when run as
a subprocess.

Below is a short program to demo.  (I use this on a test file tree
that is at ftp://joshua.smcvt.edu/pub/hefferon/a.zip if anyone
is interested.)


import subprocess
import glob

for fn in glob.glob('a*/*'):
cmd=['/usr/bin/file',fn]
cmdStr=" ".join(cmd)
try:
 
p=subprocess.Popen(cmdStr,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr)=(p.stdin,p.stdout,p.stderr)
stdoutContent=child_stdout.read()
except Exception, err:
mesg=u"unable to execute %s" % (repr(cmdStr),)
raise StandardError, mesg+": "+str(err)
if (p.returncode):
mesg=u"trouble executing %s" % (repr(cmdStr),)
raise StandardError, mesg+": "+repr(p.returncode)
print "result: ",stdoutContent
print "done"


I've put a transcript of what happens at the bottom of this message.
One file (in the test tree it is "eqchange.txt") gives no output from
the above program, but does give an output when I use "file" at the
command line.

Specifying "-m/usr/share/file/magic" in the "file" call doesn't
change
that the command line and subprocess calls act differently, so it is
not just a question of different environments causing the system to
use different "magic" files.  Changing the PIPE's to files, then
closing
and reopening them also does not matter, I believe.

In short I expected subprocess to just mimic my typing it in.  Is
there some reason "file" doesn't act this way, and is there some
way to make it do so?

I have Python 2.4.4 running on Ubuntu.  Thank you for any suggestions,
Jim

-transcript (edited to shorten)
$ python test.py
result:  acrotex/readme.txt: ASCII English text, with CRLF line
terminators

result:  acrotex/eq2db.ins: ASCII English text, with CRLF line
terminators

result:  acrotex/eqchange.txt:

result:  acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line
terminators
result:  acrotex/doc: directory

done

$ file acrotex/eqchange.txt
acrotex/eqchange.txt: ISO-8859 English text, with CRLF line
terminators
$ file acrotex/eqchange.txt 1> test.out
$ cat test.out
acrotex/eqchange.txt: ISO-8859 English text, with CRLF line
terminators
$ file acrotex/eqchange.txt 2> test.out
acrotex/eqchange.txt: ISO-8859 English text, with CRLF line
terminators
$ cat test.out
$

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


Baffled on Windows.

2007-06-07 Thread Neil Cerutti
I have the following Python program:

import win32com.client
print 'Huh?' # Actually, it says something profain.


Running this program with 2.5.1 causes another Python script in
the same directory to be loaded and run (specifically the import
causes it), and a .pyc file is created from that list.

The 'other' program is called 'new.py'. Is that what's causing
my problem?

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


Re: Integer division

2007-06-07 Thread Hamish Moffatt
[EMAIL PROTECTED] wrote:
> On Jun 7, 2:15 pm, Hamish Moffatt <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>> Hello all,
>>>  I have two integers and I want to divide one by another, and want to
>>> get an integer result which is the higher side whenever the result is
>>> a fraction.
>>>  3/2 => 1 # Usual behavior
>>>  some_func(3, 2) => 2 # Wanted
>>> Any easier solution other than int(math.ceil(float(3)/2))
>> The normal solution is to add (divisor-1) to the dividend before division.
>>
>> Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct.
>> But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct.
> 
> What about this?
> 
 def div_ceil(a, b):
> ... if a%b:
> ... return ((a/b)+1)
> ... else:
> ... return (a/b)

Yes, although it's not as short or as fast (probably as my version):

def div_ceil(a, b):
 return ((a+(b-1))/b)



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


Re: Baffled on Windows.

2007-06-07 Thread Tim Golden
Neil Cerutti wrote:
> I have the following Python program:
> 
> import win32com.client
> print 'Huh?' # Actually, it says something profain.
> 
> 
> Running this program with 2.5.1 causes another Python script in
> the same directory to be loaded and run (specifically the import
> causes it), and a .pyc file is created from that list.
> 
> The 'other' program is called 'new.py'. Is that what's causing
> my problem?

A useful technique on these occasions is to use the -v
switch when starting python. If I do nothing more than
import win32com.client, watch what happens:

python -v -c "import win32com.client" 2> python-startup.txt
grep "new" python-startup.txt
.
.
# c:\python24\lib\new.pyc matches c:\python24\lib\new.py
import new # precompiled from c:\python24\lib\new.pyc
# cleanup[2] new

So somewhere in there a module called "new" is being
imported from standard library and, yes, you are
shadowing that module by your own one of the same
name.

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

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


FTPLIB fails to retreive the remote file

2007-06-07 Thread Hrusikesa Patro
Hi All,

I'm trying to download a remote file through FTP. Here's the script:

###
#!/usr/bin/env python
import ftplib
import os
import time

ddir="C:\\ftp"
os.chdir(ddir)
f=ftplib.FTP("10.2.2.1", "user", "user123")
f.cwd("/home/protocol/cccdb/dumps/")

# define filename
day=time.strftime("%Y.%d.%m")
file2="mq20-%s-cdbdump.xml.md5" % (day)

#To debug
pwd = f.pwd()
print pwd
print file2

# get the remote file to the local directory
f.retrbinary('RETR %s' % file2, open(file2,"wb").write)
f.close()
###


*Output:*
>>> execfile("ftp.py")
/home/protocol/cccdb/dumps
mq20-2007.07.06-cdbdump.xml.md5
Traceback (most recent call last):
  File "", line 1, in ?
  File "ftp.py", line 44, in ?
f.retrbinary('RETR %s' % file2, open(file2,"wb").write)
  File "t:\Python23\lib\ftplib.py", line 379, in retrbinary
conn = self.transfercmd(cmd, rest)
  File "t:\Python23\lib\ftplib.py", line 345, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
  File "t:\Python23\lib\ftplib.py", line 324, in ntransfercmd
conn.connect(sa)
  File "", line 1, in connect
socket.error: (10060, 'Operation timed out')
>>>

What's gone wrong?

Rgs,
Hrusi

***  Aricent-Unclassified   ***
"DISCLAIMER: This message is proprietary to Aricent and is intended solely for 
the use of 
the individual to whom it is addressed. It may contain privileged or 
confidential information and should not be 
circulated or used for any purpose other than for what it is intended. If you 
have received this message in error, 
please notify the originator immediately. If you are not the intended 
recipient, you are notified that you are strictly
prohibited from using, copying, altering, or disclosing the contents of this 
message. Aricent accepts no responsibility for 
loss or damage arising from the use of the information transmitted by this 
email including damage from virus."
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: subprocess leaves child living

2007-06-07 Thread Thomas Dybdahl Ahle
Den Thu, 07 Jun 2007 07:00:53 + skrev reed:

> On Jun 5, 7:58 am, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
>> Hi, When I do a small program like
>>
>> from subprocess import Popen
>> popen = Popen(["ping", "google.com"]) from time import sleep
>> sleep(100)
>>
>> start it and kill it, the ping process lives on. Is there a way to
>> ensure that the ping process is always killed when the python process
>> is?
>> I can't use atexit, as ping then isn't killed when python is killed "in
>> the hard way"
> 
> 
> 
> pid = popen.pid
> pidfile = open('/usr/local/var/somefile.pid', 'w') pidfile.write('pid')
> pidfile.close()

> then you can check if it is still running when your ?program? restarts
> and can kill it.

If it restarts yeah.

> maybe not the perfect answer, but it answers an imperfect question.

Any details you need?
-- 
http://mail.python.org/mailman/listinfo/python-list


Lack of += and -= operators in Pyrex?

2007-06-07 Thread Skip Montanaro
I'm experimenting a bit with Pyrex and like it pretty well so far.
While converting a module from Python to Pyrex I noticed it complains
about the use of the += and -= assignment operators.  The fix is
obviously pretty trivial.  I didn't notice any mention in the Pyrex
docs as a difference between Python and Pyrex though.  Was I mistaken?

In case it makes any difference, the structure of the couple
statements I needed to change was

obj.attr.subattr += self.attr

Thx,

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


Tkinter custom drawing

2007-06-07 Thread Xavier Bérard
Hello everyone,

I am wondering if there is a way to use custom drawing in Tkinter.
I've been using it for few months, and all I know about custom drawing
is to draw directly on a Canvas with such methods as "create_line",
"create_rectangle", etc.

Now, the problem, is that I have already plenty of widgets on my
screen. I just want to draw over them, which is a bit difficult in my
comprehension of things.

My perfect solution was to put temporary invisible Canvas when I want
do use draw methods, but such thing doesn't exist (as far as I could
search in this community's posts).

Anyone have a clue ?

Thanks,
Xavier Berard

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


pickling problem

2007-06-07 Thread Brian Blais
Hello,

I have a somewhat nested dict that I want to pickle, but it (sometimes) 
contains some
no-no's  (specifically, in this case, functions).  I know I can't pickle them, 
but I
would like to be able to pickle the rest of the dict.  Is there a good way to 
be able
to walk through a dict, and take out all of the non-pickleable objects?  I could
replace them with something else (a tag of some sort, for me to reconstruct 
things
later).


thanks,

Brian Blais

-- 
-

  [EMAIL PROTECTED]
  http://web.bryant.edu/~bblais

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


Re: Bragging about Python

2007-06-07 Thread Mathias Panzenboeck
Steve Howell schrieb:
> --- "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> wrote:
> 
>> Is there a resource somewhere on the net that can be
>> used to quickly
>> and effectively show Python's strengths to
>> non-Python programmers?
>> Small examples that will make them go "Wow, that
>> _is_ neat"?
>>
> 
> 15 small programs here:
> 
> http://wiki.python.org/moin/SimplePrograms
> 

IMHO a few python goodies are missing there.
e.g. generator functions:

# generic fibonacci without upper bound:
def fib():
parent_rabbits, baby_rabbits = 1, 1
while True:
yield baby_rabbits
parent_rabbits, baby_rabbits = baby_rabbits, parent_rabbits + 
baby_rabbits


# only calculate and print the first 100 fibonacci numbers:
from itertools import islice

for baby_rabbits in islice(fib(),100):
print 'This generation has %d rabbits' % baby_rabbits
-- 
http://mail.python.org/mailman/listinfo/python-list


url to image

2007-06-07 Thread sononix
just wondering are there any snippets out there where you can convert
a url to an image using python

I have be trying to use

webbrowser.open("www.mypage.com")

with printscreen but I have no means of finding out when the page url
is fully loaded

any tips

tks
M

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


open function fail after running a day

2007-06-07 Thread alexteo21
I have created a script using python that will batch process data
files every hour
The script is running on Solaris.  Python version 2.3.3

t=open(filename,'rb')
data=t.read()
#processing data...
t.close()

The script is working fine on the day of execution.
It is able to process the data files very hour.  However, the
processing fail one day later i.e. the date increment by 1.

Traceback (most recent call last):
  File "./alexCopy.py", line 459, in processRequestModule
sanityTestSteps(reqId,model)
  File "./alexCopy.py", line 699, in sanityTestSteps
t = open(filename, 'rb')
IOError: [Errno 24] Too many open files:

I have explicitly closed the file.  Is there something else I need to
do?

Appreciate your comments

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


Re: Why can not catch the inner exception

2007-06-07 Thread Mark T


"人言落日是天涯,望极天涯不见家" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Please see the follow code,  I can not catch the exception " IOError"
raised from shutil.copyfile() , why?
   try:
   if (DEST_TYPE & TYPE_FTP):
   fn = oname
   ftpc.UploadFile(f, fn)
   else:
   fn = os.path.join(dst, oname)
   shutil.copyfile(f, fn)

    other code

   except [IOError, FtpcException],why:
   num = 0
   print >>sys.stderr, "can not copy '%s' to '%s':
%s"%(f, fn, why)
   ERR_NUM += 1

I must do like this:
   try:
   if (DEST_TYPE & TYPE_FTP):
   fn = oname
   ftpc.UploadFile(f, fn)
   else:
   fn = os.path.join(dst, oname)
   try:
shutil.copyfile(f, fn)
   except IOError:
  

    other code

   except [IOError, FtpcException],why:
   num = 0
   print >>sys.stderr, "can not copy '%s' to '%s':
%s"%(f, fn, why)
   ERR_NUM += 1

Thanks!



你好,

Use a tuple (IOError,FtpcException) instead of a list in the except 
statement and it works.


--马克

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

Re: open function fail after running a day

2007-06-07 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 alexteo21 <[EMAIL PROTECTED]> wrote:

> The script is working fine on the day of execution.
> It is able to process the data files very hour.  However, the
> processing fail one day later i.e. the date increment by 1.
> 
> Traceback (most recent call last):
>   File "./alexCopy.py", line 459, in processRequestModule
> sanityTestSteps(reqId,model)
>   File "./alexCopy.py", line 699, in sanityTestSteps
> t = open(filename, 'rb')
> IOError: [Errno 24] Too many open files:
> 
> I have explicitly closed the file.  Is there something else I need to
> do?

Sounds like the .close() isn't getting executed as you think. Try using 
the logging module to log a line immediately before each open and close 
so that you can ensure you're really closing all the files. 
Alternatively, some other bit of code my be the guilty party. A utility 
like fstat can show you who has files open.

Good luck

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: MySQL InterfaceError

2007-06-07 Thread Joe
> Huh the only thing I can find on InterfaceError is "Errors related to
> the database interface and not the database itself." You might be able
> to get some info from connection.info() . . .

Yeah, I wish there was more documentation about this type of error.  The
only thing info() tells me is that the connection is open through id ##.

> Are you using utf8? MySQLdb seems to have some problems with that.
> Also, I assume you've tried catching the error and printing the error
> message, right?

Yes, we are using utf8.  What kind of problems can be seen with it?  This is
all I have run across so far.  What type of encoding would you suggest?  I
am still new at some of this stuff, so if you could possibly explain
(off-topic, so a link is fine) the differences between database encodings I
would be grateful.

And, yes, printing the error message returns absolutely nothing.  The tuple
following InterfaceError is both the error code and message.  Unfortunately,
it will only give me (0, '') which isn't much help.

Thanks again!

Jough 

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


Re: Lack of += and -= operators in Pyrex?

2007-06-07 Thread Skip Montanaro
> ... I noticed it complains
> about the use of the += and -= assignment operators.  The fix is
> obviously pretty trivial.  I didn't notice any mention in the Pyrex
> docs as a difference between Python and Pyrex though.  Was I mistaken?

Never mind.  I missed the bit where it said they haven't yet been implemented.

Sorry for the noise...

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


Re: Baffled on Windows.

2007-06-07 Thread BartlebyScrivener
On Jun 7, 8:17 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> I have the following Python program:
>
> Running this program with 2.5.1 causes another Python script in
> the same directory to be loaded . . . 'new.py'

A good habit for naming your scripts: If you have a script and you
want to name it text.py, or list.py or new.py or old.py or some common
name that might be found in the thousand and one other modules and
programs in your various installations, just use my_text.py or
my_list.py or neil_new.py or something to reduce the chances that
you'll be shadowing without knowing it.

rick


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


Re: Integer division

2007-06-07 Thread Sion Arrowsmith
Hamish Moffatt  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] wrote:
> def div_ceil(a, b):
>> ... if a%b:
>> ... return ((a/b)+1)
>> ... else:
>> ... return (a/b)
>
>Yes, although it's not as short or as fast (probably as my version):
>
>def div_ceil(a, b):
> return ((a+(b-1))/b)

If that's what you care about:

$ python -mtimeit -s 'def divc1(a,b): return (a+b-1)/b' 'divc1(3,2)'
100 loops, best of 3: 0.443 usec per loop
$ python -mtimeit -s 'def divc2(a,b): return -(-a/b)' 'divc2(3,2)'
100 loops, best of 3: 0.331 usec per loop

Also, note:

>>> divc2(sys.maxint, 2)
1073741824
>>> divc1(sys.maxint, 2)
1073741824L

which is going to cause problems with sys.version_info < (2, 3) .
(Or do I mean (2, 2)? I don't have a 2.2 to hand.)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ctypes: error passing a list of str to a fortran dll

2007-06-07 Thread luis
On 5 jun, 06:15, Charles Sanders <[EMAIL PROTECTED]>
wrote:
> luis wrote:
> > I'm using ctypes to call afortrandllfrom python. I have no problems
> > passing integer and double arryas, but I have an error with str arrys.
> > For example:
>
> [snip]
>
> I do not know about MicrosoftFortrancompilers (your mention
> ofdllindicates you are probably using MS), nor much about
> Python, but the C equivalent of a givenFortrancall is operating
> system and compiler dependent. You should consult theFortran
> compiler manual for the compiler used to create theDLL.
>
> Despite this, many (but not all) C toFortraninterfaces have
> the following characteristics
>
> + C name isFortranname in lower case
> +FortranREAL, DOUBLE PRECISION, INTEGER etc parameters
>   are pointers to the parameter in C, ie float*, etc
> +FortranREAL etc arrays are pointers in C (same as
>   C arrays decay to pointers).
> +FortranCHARACTER and CHARACTER arrays are passed as TWO
>   parameters, one a pointer to the start of the variable
>   or array, and the other the length as an integer, not
>   a pointer. The length parameters follow all other
>   parameters, in order of the character variables/arrays.
>
> Variations I have seen (all on Unix) include using upper case
> instead of lower, prepending (or postpending) an underscore (or
> other character(s)) to the subroutine or function name, and
> using special "character descriptors" (packing address and
> length into one "word") for character variables. There are
> almost certainly more variations that I have not seen.
>
> For example, given aFORTRANdeclaration
>
> SUBROUTINE X( CV, RV, CA, N )
> CHARACTER*(*) CV
> REAL  RV
> CHARACTER*(*) CA(*)
> INTEGER   N
>
> The C equivalent is likely to be
>
> void x( char *pcv, float *prv, char *pca, int *pn,
> int lv, int la)
>
> Where lv will hold the length  of cv and la the length of
> each element of ca (required to be the same for all elements
> of the array).Fortranuses fixed length character strings,
> padded with blanks.
>
> Given the error message
>
>  > ValueError: Procedure probably called with not enough
>  > arguments (4 bytes missing)
>
> I suspect that yourFortrancompiler is one of the many which
> do this, and the missing 4 bytes are the integer length of
> each element of the character array.
>
> Also, I noticed you seem to be passing an array of character
> pointers rather than an array of characters. It is doubtful thatFortrancan 
> handle this. You will probably have to pad the strings
> to a maximal length with spaces, concatanate then into one big
> string, and pass this by reference together with their padded
> length. YourFortranmay (but probably won't) have extensions
> that allow you to pass an array of character pointers.
>
> Charles

The solution proposed by Jugoslav Dujic, from comp lang fortran is

#Python script calling fortran subroutine
from ctypes import *
ap = windll.LoadLibrary(self.locationDll)
ap.TEST_02.restype=None
myCadena='D:\BBDD\PythonScripts\pru.txt'
strLen=len(myCadena)
pf_myCadena = c_char_p(myCadena)
pf_srLen = c_int(strLen)
ap.TEST_02(pf_myCadena,pf_srLen)

!fortran dll
subroutine TEST_02(s)
  !DEC$ ATTRIBUTES DLLEXPORT :: TEST_02
  !DEC$ATTRIBUTES REFERENCE:: s
  !INTEGER(4):: n
  CHARACTER(*):: s

  open (unit=31,file=trim(s))
  write(31,'(f0.1)') 1.0
  write(31,*) trim(s)
  write(31,'(i0)') len_trim(s)
  close(31)
  return
END subroutine

Regards

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


Re: Baffled on Windows.

2007-06-07 Thread Robin Becker
BartlebyScrivener wrote:
> On Jun 7, 8:17 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:

> A good habit for naming your scripts: If you have a script and you
> want to name it text.py, or list.py or new.py or old.py or some common
> name that might be found in the thousand and one other modules and
> programs in your various installations, just use my_text.py or
> my_list.py or neil_new.py or something to reduce the chances that
> you'll be shadowing without knowing it.
> 
> rick

using your advice we will start getting problems where my_new is shadowed so 
then we start having to recur and we'll have names like

my_my_new.py my_my_list.py .. my_my_my_new.py .

I leave as an exercise the algorithm which chooses the appropriate version of 
new/list to use :)
-- 
Robin Becker

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


Re: Designing a graph study program

2007-06-07 Thread andrea
On 10 Mag, 16:52, Alexander Schliep <[EMAIL PROTECTED]> wrote:
> andrea <[EMAIL PROTECTED]> writes:
> > On 9 Mag, 09:10, Alexander Schliep <[EMAIL PROTECTED]> wrote:
> >> Check outhttp://gato.sf.net(LGPLlicense). It does exactly what you
> >> want to do and there is a binary for MacOS X. Algorithms are implemented
> >> using Gato's graph class and rudimentary visualizations you get for free
> >> by replacing standard data structures (e.g., a vertex queue) by
> >> animated ones (AnimatedVertexQueue).
>
> > Very very nice well done!
>
> Thanks.
>
> > I'd like to do something similar, just to learn something new...
>
> Gato is open source and I'd be happy to collaborate. There are quite a
> few areas (e.g. SVG export, displays for data structure contents, more
> complete 3D support, polygon edges, running backwards?) which need
> work.
>
> > Could you explain me how you designed it?? How is the step mechanism
> > done??
>
> The algorithm is executed by a subclass of the Python debugger (see
> Gato.py).  A Tk event mechanism is used to step to the next line if
> you are in running mode. Otherwise the user steps manually. The
> visualizations are done with animated data structures, which animate
> changes to their internal state with respect to the graph: e.g., when
> you add or remove v to/from an AnimatedVertexQueue it changes v's
> color.
>
> Tk has a canvas which does object-oriented drawing. A line is not
> just a bunch of pixels but rather an object which you can move,
> scale, has callbacks. I dislike Tcl, but Tk is amazing, even it
> it looks 1980s.
>
> There is a 
> paperhttp://algorithmics.molgen.mpg.de/preprints/2000-CATBox-MTCM.pdf
> describing the ideas.
>
> Best,
> Alexander

Ok thanks a lot for the explanation Alexander...

Well I changed my implementation of edges and nodes to this:

class node:
"""nodi di un grafo"""
def __init__(self, label, color=None, parent=None, distance=None):
self.label = label
self.color = color
self.parent = parent
self.distance = distance

def __eq__(self,y):
"""uguaglianza fra nodi"""
return self.label == y.label

def __repr__(self):
"""docstring for __repr__"""
return str(self.label)


class edge: # CHANGED tutta la gestione di nodi e lati
"""lato di un grafo"""
def __init__(self, u, v, directed=False, w=1):
"due lati ed eventualmente il peso associato"
self.u = u
self.v = v
self.w = w
self.directed = directed


def __repr__(self):
"""docstring for __repr__"""
if self.directed:
sym = " --> "
else:
sym = " --- "
return str(self.u) + sym + str(self.v)

def __eq__(self,y):
if self.directed != y.directed:
return False
r = (self.u == y.u and self.v == y.v)
l = (self.v == y.u and self.u == y.v)
if self.directed: # gia controllato che non siano diversi
return r
else:
return r or l


Does it make sense??
But now I have some troubles with all the rest ;)
For example this code

def make_adj_list(self,nodes,edges):
"""crea la lista di adiacenza"""
adj_list = {}
for v in nodes:
adj_list[v] = []
   ...
builds an adjacency list of the graph, but now the object Node is not
hashable of course!
How do I manage this? I think I can use the label
adj_list[v.label] = [u.label, etc etc]
but then I need another dictionary to go from labels to objects, it's
not difficult but look ugly to me, other solutions??

Thanks a lot

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


Re: Tkinter custom drawing

2007-06-07 Thread Kevin Walzer
Xavier Bérard wrote:
> 
> Now, the problem, is that I have already plenty of widgets on my
> screen. I just want to draw over them, which is a bit difficult in my
> comprehension of things.
> 

What are you trying to achieve by "drawing over" widgets?

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib error- Large file

2007-06-07 Thread Facundo Batista
[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/


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


Re: Help a C++ escapee!

2007-06-07 Thread Jason
On Jun 7, 1:59 am, "Simon Pickles" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Can someone help me leave the murky c++ world and enter shiny pythonland?
>
> I have a problem with importing and global variables, here's my code:
[snip!]
> When run, I come unstuck here:
>
> self.clientSocket, self.clientAddress = network.accept()
>
> I get a nameError on 'network', yet it is one in the global namespace,
> defined in server.py before CServerThread.Listen() is called.
>
> In c++, I understood how to declare variables, here I have a problem. Its
> like I need an extern statement from c++.
>
> Can anyone clarify this for me?

The others have covered your problem.  I'd just like to add a little
detail.

As the others have mentioned, global variables reside in their module
namespace.  There is no truly "global" namespace, and that hasn't
really shown up as a problem in Python.  There are two tricks to this:

  1)  Modules are only executed once, at the first import.  Every
additional import merely gets the module object, but does not execute
the code again.  Try adding a print statement outside all class and
function statements in a module, then import it multiple times.
You'll only see the results of the print statement once.

You can also start up python with the "-v" flag.  Python will then
tell you whenever it executes a module.

This means that you can have a "global" module.  Create a Python
module with all the variables that you want, and just import that
module in all places that need those variables.  If you find yourself
stuffing a huge number of variables into your global module, you
probably need to rethink your program design.

Otherwise, put the global data in the various modules that create and
update it.  Usually, your other code will only need to access that
data under more rare conditions.

If you absolutely need a module to be re-executed, the "reload"
function will do what you want.

  2)  Modules do not have to be imported at the start of the file.  A
module import statement can occur any time code is executed.  By
convention, we place the import statement at the beginning of the
block where we use it.

Remember that Python isn't C++.  If you place an import statement in a
function, Python doesn't try to import that statement until the
function is called.  This is very different from C/C++'s #include
preprocessor statements.

If you're having problems with circular references, the import
statement can usually
be moved inside of functions or methods that need them, or the files
can be refactored to  get rid of the circular reference.

Here's something that shows both points.  I started python by typing
in "python -v".  There's a large number of imported modules that
Python automatically loads.  After that finishes:
>>> def spam(x):
... x = 5 * x
... import math   # Math won't be imported until this function is
called
... return math.pow(x, 2)
...
>>> spam(1) # This should import the math module, executing its contents
import math # builtin
25.0
>>> spam(2) # spam() will now use the previously import math module.  (This is 
>>> fast)
100.0

Hope this helps!

  --Jason

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


Re: Why can not catch the inner exception

2007-06-07 Thread kelvin.you
On 6 7 ,   10 53 , "Mark T" <[EMAIL PROTECTED]> wrote:
> "   " <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
>
>
>
>
> > Please see the follow code,  I can not catch the exception " IOError"
> > raised from shutil.copyfile() , why?
> >try:
> >if (DEST_TYPE & TYPE_FTP):
> >fn = oname
> >ftpc.UploadFile(f, fn)
> >else:
> >fn = os.path.join(dst, oname)
> >shutil.copyfile(f, fn)
>
> > other code
>
> >except [IOError, FtpcException],why:
> >num = 0
> >print >>sys.stderr, "can not copy '%s' to '%s':
> > %s"%(f, fn, why)
> >ERR_NUM += 1
>
> > I must do like this:
> >try:
> >if (DEST_TYPE & TYPE_FTP):
> >fn = oname
> >ftpc.UploadFile(f, fn)
> >else:
> >fn = os.path.join(dst, oname)
> >try:
> > shutil.copyfile(f, fn)
> >except IOError:
> >   
>
> > other code
>
> >except [IOError, FtpcException],why:
> >num = 0
> >print >>sys.stderr, "can not copy '%s' to '%s':
> > %s"%(f, fn, why)
> >ERR_NUM += 1
>
> > Thanks!
>
>   ,
>
> Use a tuple (IOError,FtpcException) instead of a list in the except
> statement and it works.
>
> --  - -
>
> - -

Thank you!
  :-)

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


Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread dmoore
Hi folks,

I've seen the following issue come up in multiple posts to this
mailing list:

I have a python program that spawns a child process with popen or
popen2 or popen3 or popen2.popen2 etc.
the child process is interactive: it asks for input then spits out
some output, asks for more input then spits out some output. for
example, consider the trivial child program:

print "welcome"
print ">",
s=raw_input()
while s!='exit':
print "you entered:",s
print ">",
s=raw_input()

Now I may be completely wrong about this (I did play with popen for a
very long time before writing this message), but it appears that none
of the popen variants allow for a sequence of reads and writes to/from
this child. that is, if I read from the open pipe's output I will
never be able to write the input for the child because the parent
program will block on read until eof (I will have similar blocking
problems if I start with write - using readline does not seem to
help).

the standard proposed remedy I have seen on this list is to use Unix-
only select/fctl, or otherwise dig into the bowls of the win32 api, or
download some half-complete sourceforge process control project. All
well and good, but unsatisfying for writing platform independent code.

it turns out that there is at least one open source multi-platform
(read: win32/linux) api that does handle synchronous I/O with the
child: wxWidgets and wxPython using the class wxProcess. Now the
wxWidgets implementation is far from perfect, but it at least allows a
program to test for new input on the child's stdout and read stdout/
write stdout in a non-blocking way. However, I find it frustrating
that I have to import wx just to have useable interactive pipes in my
python scripts when I would expect this to be part of the native
python implementation.

Anybody have any thoughts on this? Do I have my story straight? (the
popen variants can't handle this case and there are no other
alternatives in the standard python distro) Is there some place I can
submit this as a feature request? (Python dev?)

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


running a random function

2007-06-07 Thread David Bear
I would like to write some code that would randomly select a function from a
list of functions and call it. I was looking in the globals names space and
randomly selecting items that were of type function.. but I didn't see a
way of actually running the function.

Any pointers?

-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL InterfaceError

2007-06-07 Thread kaens
On 6/7/07, Joe <[EMAIL PROTECTED]> wrote:
> > Huh the only thing I can find on InterfaceError is "Errors related to
> > the database interface and not the database itself." You might be able
> > to get some info from connection.info() . . .
>
> Yeah, I wish there was more documentation about this type of error.  The
> only thing info() tells me is that the connection is open through id ##.
>
> > Are you using utf8? MySQLdb seems to have some problems with that.
> > Also, I assume you've tried catching the error and printing the error
> > message, right?
>
> Yes, we are using utf8.  What kind of problems can be seen with it?  This is
> all I have run across so far.  What type of encoding would you suggest?  I
> am still new at some of this stuff, so if you could possibly explain
> (off-topic, so a link is fine) the differences between database encodings I
> would be grateful.
>
> And, yes, printing the error message returns absolutely nothing.  The tuple
> following InterfaceError is both the error code and message.  Unfortunately,
> it will only give me (0, '') which isn't much help.
>
> Thanks again!
>
> Jough
>
>

I really don't know what kinds of errors have cropped up with utf8, or
what encoding you should use. The one utf8 error I saw online was
related to the character_set_name() call - you could try commenting
that out, and all the references to the variable set, and see if your
queries work then.

I don't know if that's your problem or not.

I guess you should go to the MySQLdb site and open a bug report there
or something. Wish I knew enough about it to help you out more, but
really, I just use it, and I've yet to have a problem with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


updating db with csv

2007-06-07 Thread moishyyehuda
#1 If any one familiar with godaddy hosting. They have apparently have
a hosing server i.e.(scripts, html files etc.), and a server for
databases. How can I import from my script,  with a csv. if the db is
on a different server than the script server.

#2 I would like to update and insert with the same csv file. Is there
a way to tell the database for some lines to update, and for some
lines to insert.

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


Re: running a random function

2007-06-07 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, David Bear wrote:

> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.

If you have a function or callable you call it with the "call operator",
which are parenthesis:

In [8]: int
Out[8]: 

In [9]: int()
Out[9]: 0

For a random selection of an element from a list look at the
`random.choice()` function.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running a random function

2007-06-07 Thread Matimus
How are you making the list of functions? Something like this:

[code]
fs = []
for k,f in globals():
if callable(f):
fs.append(f)
[/code]

Then to call a random one (assuming they all take no parameters):

[code]
import random
random.choice(fs)()
[/code]

Or maybe you only have the name of the function, this should work:

[code]
globals()[name]()
[/code]

Does this help? I'm not really clear on what you are asking for.

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


Re: running a random function

2007-06-07 Thread Brian van den Broek
David Bear said unto the world upon 06/07/2007 11:56 AM:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.
> 
> Any pointers?
> 

Unless I've missed your meaning:

 >>> import random
 >>> def f(): print 42
...
 >>> def g(): print 24
...
 >>> funcs = [f,g]
 >>> random.choice(funcs)()
24


Best,

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


Re: Baffled on Windows.

2007-06-07 Thread Neil Cerutti
On 2007-06-07, Robin Becker <[EMAIL PROTECTED]> wrote:
> BartlebyScrivener wrote:
>> On Jun 7, 8:17 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> 
>> A good habit for naming your scripts: If you have a script and you
>> want to name it text.py, or list.py or new.py or old.py or some common
>> name that might be found in the thousand and one other modules and
>> programs in your various installations, just use my_text.py or
>> my_list.py or neil_new.py or something to reduce the chances that
>> you'll be shadowing without knowing it.
>> 
>> rick
>
> using your advice we will start getting problems where my_new
> is shadowed so then we start having to recur and we'll have
> names like
>
> my_my_new.py my_my_list.py .. my_my_my_new.py .
>
> I leave as an exercise the algorithm which chooses the
> appropriate version of new/list to use :)

Thanks all for the helpful replies.

I'll just memorize the names of all the Python modules in
existence to eliminate this source of errors once and for all.

Or possibly I'll just rename my scripts things whenever this
happens. ;)

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


Re: running a random function

2007-06-07 Thread Dustan
On Jun 7, 10:56 am, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function..

Careful!!! You don't want to destroy your computer by accident.

> but I didn't see a
> way of actually running the function.

What do you mean? foo is a function; here's how you run it:

foo()

> Any pointers?

Given a list of functions, it would simply be, given the list of
functions bar (untested):

import random
random.choice(bar)()

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


easiest way to count memory eaten by call to Python func?

2007-06-07 Thread dmitrey
hi all,
which way is the simplest for now to obtain the memory amount eaten by
call to Python  'myfunc' function?
Thx, D

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


Re: open function fail after running a day

2007-06-07 Thread Vinay Sajip
On Jun 7, 3:33 pm, alexteo21 <[EMAIL PROTECTED]> wrote:
> I have created a script using python that will batch process data
> files every hour
> The script is running on Solaris.  Python version 2.3.3
>
> t=open(filename,'rb')
> data=t.read()
> #processing data...
> t.close()

Try the following approach:

t=open(filename,'rb')
try:
  data=t.read()
  #processing data...
finally:
  t.close()

and see if that improves matters. If you want to add logging for a
quick check, then...

import logging

t=open(filename,'rb')
try:
  data=t.read()
  #processing data...
except:
  logging.exception("Failed to process file %r", filename)
finally:
  t.close()

Regards,

Vinay Sajip

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


Re: running a random function

2007-06-07 Thread Roberto Bonvallet
On 7 jun, 11:56, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.

Try this:

def f(x):
print "Calling f with arg %s" % x
def g(x):
print "Calling g with arg %s" % x
def h(x):
print "Calling h with arg %s" % x

import random
functions = [f, g, h]
for i in range(10):
random.choice(functions)(25)

HTH, cheers.
--
Roberto Bonvallet

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


Re: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread Nick Craig-Wood
dmoore <[EMAIL PROTECTED]> wrote:
>  I've seen the following issue come up in multiple posts to this
>  mailing list:
> 
>  I have a python program that spawns a child process with popen or
>  popen2 or popen3 or popen2.popen2 etc.
>  the child process is interactive: it asks for input then spits out
>  some output, asks for more input then spits out some output. for
>  example, consider the trivial child program:
> 
>  print "welcome"
>  print ">",
>  s=raw_input()
>  while s!='exit':
>  print "you entered:",s
>  print ">",
>  s=raw_input()
> 
>  Now I may be completely wrong about this (I did play with popen for a
>  very long time before writing this message), but it appears that none
>  of the popen variants allow for a sequence of reads and writes to/from
>  this child. that is, if I read from the open pipe's output I will
>  never be able to write the input for the child because the parent
>  program will block on read until eof (I will have similar blocking
>  problems if I start with write - using readline does not seem to
>  help).

You are correct.

>  the standard proposed remedy I have seen on this list is to use Unix-
>  only select/fctl, or otherwise dig into the bowls of the win32 api, or
>  download some half-complete sourceforge process control project.

If you are referring to pexpect I've found it works well - unix only
though.  I've not noticed it being half complete.

There is also a recipe for a non-blocking subprocess - see

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

> All well and good, but unsatisfying for writing platform independent code.
> 
>  it turns out that there is at least one open source multi-platform
>  (read: win32/linux) api that does handle synchronous I/O with the
>  child: wxWidgets and wxPython using the class wxProcess. Now the
>  wxWidgets implementation is far from perfect, but it at least allows a
>  program to test for new input on the child's stdout and read stdout/
>  write stdout in a non-blocking way.

Interesting I didn't know about that - I shall try it!

>  However, I find it frustrating
>  that I have to import wx just to have useable interactive pipes in my
>  python scripts when I would expect this to be part of the native
>  python implementation.
> 
>  Anybody have any thoughts on this? Do I have my story straight? (the
>  popen variants can't handle this case and there are no other
>  alternatives in the standard python distro) Is there some place I can
>  submit this as a feature request? (Python dev?)

The non-blocking subprocess would make a good start for a stdlib
submission.

It should really optionally use ptys under unix too otherwise you'll
never be able to script passwd etc.  An interface a bit like pexpect
wpuld be useful too (ie scan for these regexps or timeout and return a
match object).

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running a random function

2007-06-07 Thread Stebanoid
On 7, 19:56, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.
>
> Any pointers?
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --

if you have a list of functions you can try this:

import random
import math
m[int(math.ceil(random.random()))]() #seems like Lisp code :)

but what about functions arguments?
Strange task... Very strange

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


pyExcelerator Protection insert_bitmap

2007-06-07 Thread pythonwin pythonwin

Good evening!

say, please, as in *.xls to insert an unscreened picture?

example: image.py

but a picture in OpenOficce is not represented :(
OS - windows XP, debian etch
pyExcelerator 0.6.3a-1
#!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 Kiseliov Roman

__rev_id__ = """$Id: image.py,v 1.3 2005/03/27 12:47:06 rvk Exp $"""


from pyExcelerator import *

w = Workbook()
ws = w.add_sheet('Image')



class Protection(Formatting.Protection):
def __init__(self, cell_locked,formula_hidden):
self.cell_locked = cell_locked
self.formula_hidden = formula_hidden

protection = Protection(0,0)

t = ((protection.cell_locked & 0x01) << 0) | ((protection.formula_hidden & 0x01) << 1)

print t


style = XFStyle()
style.protection = protection


ws.write(2, 2, '1',  style)
ws.insert_bitmap('python.bmp', 2, 2)
ws.insert_bitmap('python.bmp', 10, 2)


ws.protect = False
ws.wnd_protect = False
ws.obj_protect = False
ws.scen_protect = False

w.protect = False
w.wnd_protect = False
w.obj_protect = False


w.save('image.xls')
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: MySQL InterfaceError

2007-06-07 Thread BartlebyScrivener
On Jun 7, 10:09 am, "Joe" <[EMAIL PROTECTED]> wrote:
>
> And, yes, printing the error message returns absolutely nothing.  The tuple
> following InterfaceError is both the error code and message.  Unfortunately,
> it will only give me (0, '') which isn't much help.
>

I'm on Google groups and can't see the first part of your original
message, so don't know what query you are using. But I get that
interface error when I attempt to interpolate values from something
other than a tuple.

E.g.

SELECT item from table where item like %s

If you try to use a string, say, instead of a string in a tuple,
you'll get an interface error.

That's the only time I've gotten it.

rd

> Thanks again!
>
> Jough


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


Re: running a random function

2007-06-07 Thread Stebanoid
On 7, 19:56, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.
>
> Any pointers?
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --

if you have a list of functions you can try this:

import random
import math
m[int(math.floor(len(m)*random.random()))]()  # seems like Lisp
code :D

where m - is list of functions.
but what about functions arguments?
Strange task.. Very strange...

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


Re: Python for embedded systems with memory constraints

2007-06-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
vishnu  <[EMAIL PROTECTED]> wrote:
>Hi there,
>
>I am embedding python 2.5 on embedded system running on RTOS where I
>had strict memory constraints.
>As python is a huge malloc intensive application, I observed huge
>memory fragmentation in my system which is leading to out of memory
>after running few scripts.
>So I decided to re-initialise the python with out restarting the whole python.
>I tried to use Py_Finalise() after completion of each script , then
>call Py_Initialise as is done in below link.
>http://mail.python.org/pipermail/python-list/2001-November/114253.html
>Which in every loop it causes a leak of 10K and after some iterations
>it leaks of 200K etc. After few more runs this crashes. I read some
>where this leak was solved in 2.5, but with 2.5 also I am having
>problems
>And also I found Py_Finalise does not completely cleanup the memory,
>So how do I re-initialise my memory pool?
>
>Does anybody faced this problem earlier and got any solution hack to
>run the python for a embedded system within own managed memory pool of
>say 10MB?
>
>Any help/ideas are greatly appreciated!. Thanks in advance.

Your report is interesting and important--and surprising!  I thought
Python memory allocation is "cleaner" than you seem to be observing.

I hope one of the core Python maintainers can address this.  I haven't
worked at this level recently enough to speculate on why it's happen-
ing, nor will I soon be in a position to volunteer to research it on 
my own (although I'd eagerly contract to do so on a modestly paid
basis).  

Depending on your schedule and technology, there are lots of technical
fixes that might apply:
A.  quick-starting Python variations that encourage you
to manage memory on a whole-process level;
B.  use of one of the many Python variants (even PyPy?)
that might give you a more favorable memory profile;
C.  switch to Lua or Tcl as more easily embeddable 
alternative languages;
D.  custom memory allocator;
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who uses Python?

2007-06-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>
>"Stef Mientki" <[EMAIL PROTECTED]> wrote:
>
>> I use Python as  a replacement for MatLab,
>> and intend to use it as replacement for Delphi, AutoIt, PHP, VB.
>> And I'ld love to use it as a replacement for micro controller programming.
>
>If you have a little sub - 64k micro this is not really practical.
>
>What we have done is to define a limited virtual machine with
>a simple "assembler" language and used Python to write the
>"compiler" for it.
>
>Then you have to write the interpreter for the virtual machine
>in the native micro's code - Either using C or assembler, and
>you are away from the hardware, into a useful layer of abstraction.
>
>... well sort of - in such a small thing, you are never really far from
>the hardware, as that is what its supposed to be controlling - but
>what it definitely buys you is that your apps written in your special
>language become portable between disparate processors like say
>an ARM at the upper end and an 8031/8051 at the lower...
>
>Such "interpreters" are surprisingly little code, and they work
>well - faster than what one would expect. - often outperforming
>C code that does pass by value...
>
>- Hendrik
>

Amen!  That is, while it is indeed easy to construct examples
where Python computes a numerical result only a hundredth as 
fast as the corresponding C code, what I find far more interesting
to discuss are the (surprisingly frequent) cases where Python and
litte languages result in solutions which are *faster* at run-time,
along with being more maintainable and quick to develop.

Yet more chatter on a role for Python with specialized hardware ap-
pears in http://www.unixreview.com/documents/s=9133/ur0404e/ >.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lists - append - unique and sorted

2007-06-07 Thread Terry Reedy

"Dan Bishop" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| If you don't need the list to be sorted until you're done building it,
| you can just use:
|
| lst = sorted(set(lst))

?? looks same as
lst.sort() 



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


Re: Integer division

2007-06-07 Thread Terry Reedy

"Sion Arrowsmith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
| > 3/2 => 1 # Usual behavior
| > some_func(3, 2) => 2 # Wanted
|
| def some_func(a, b):
|return -(-a/b)
|
| And people complain about Python's behaviour regarding division of
| negative integers.

Nice.  This goes on my 'why didn't I think of that' list;-)

I was thinking of the rather pedestrian

d,r = divmod(a,b)
if r: d+=1

tjr



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


Re: TLSAbruptCloseError

2007-06-07 Thread Gabriel Genellina
En Tue, 05 Jun 2007 14:22:48 -0300, Todd Hopfinger <[EMAIL PROTECTED]>  
escribió:

> I am using TLS Lite and J2ME SecureConnection for the purposes of  
> encrypting
> traffic to/from a Java Midlet client and a multithreaded Python server.
> However, I encounter a TLSAbruptCloseError. I have tried to determine the
> cause of the exception to no avail. I understand that it has to do with
> close_notify alerts. My abbreviated code follows.
>
>
> // Server
>
>
> def sslSockRecv(conn, num):
>
> data = ''
>
> while len(data) < num:
>
> data = conn.recv(num - len(data)) #
> TLSAbruptCloseError thrown here
>
> if len(data) == 0:
>
> raise NotEnoughBytes  
> ('Too
> few bytes from client. Expected ' + str(num) + '; got ' + str(len(data)),
> num, len(data))
>
> return data

Without much analysis, shouldn't be: data += conn.recv(num - len(data)) or  
something like that?
Else you are discarding the previously received data.

-- 
Gabriel Genellina

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


Re: open function fail after running a day

2007-06-07 Thread Vinay Sajip
Try the following:

import logging

t=open(filename,'rb')
try:
data=t.read()
#processing data...
except:
logging.exception("Failed to process %r", filename)
finally:
t.close()




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


Re: Where can I suggest an enchantment for Python Zip lib?

2007-06-07 Thread Terry Reedy

"durumdara" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi!
|
| Where can I ask it?
|
| I want to ask that developers change the Python's Zip lib in the next
| versions.

On the sourceforge tracker,

http://sourceforge.net/tracker/?group_id=5470

 there is a Feature Request category. 



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


Re: Where can I suggest an enchantment for Python Zip lib?

2007-06-07 Thread Larry Bates
durumdara wrote:
> Hi!
> 
> Where can I ask it?
> 
> I want to ask that developers change the Python's Zip lib in the next
> versions.
> The Zip lib not have a callback procedure. When I zip something, I don't
> know, what is the actual position of the processing, and how many bytes
> remaining.
> It is simply rewriteable, but when I get new Python, it is forget this
> thing again...
> 
> So some callback needed for it, if possible. With this I can abort
> processing and I can show the actual state when I processing a large file.
> 
> See this thread:
> http://groups.google.com.kh/group/comp.lang.python/browse_thread/thread/c6069d12273025bf/18b9b1c286d9af7b?lnk=st&q=python+zip+callback&rnum=1#18b9b1c286d9af7b
> 
> 
> Thanks for your help:
> dd
> 
> 
You can easily find out roughly how many bytes are in your .ZIP archive
by using following:

zipbytes=Zobj.fp.tell()

Where Zobj is your zipfile instance.  You don't need a callback.

Problem is ill defined for a better solution.  You don't know how much
the "next" file will compress.  It may compress a lot, not at all or
in some situations actually grow.  So it is difficult (impossible?) to
know how many bytes are remaining.  I have a rough calculation where
I limit the files to 2Gb, but you must set aside some space for the
table of contents that gets added at the end (whose size you don't
actually know either). So I use:

maxzipbytesupperlimit=int((1L<<31)-(8*(1<<20)))

That is 2Gb-8Mb maximum TOC limit of a zip file.

I look at zipbytes add the uncompressed size of the next file, if it
exceeds maxzipbytesupperlimit, I close the file and move to the next
zip archive.  If it is smaller, I add the file to the archive.

Hope this helps.

-Larry



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


Re: open function fail after running a day

2007-06-07 Thread Vinay Sajip
Try the following (Python 2.5.x):

import logging

t=open(filename,'rb')
try:
data=t.read()
#processing data...
except:
logging.exception("Failed to process %r", filename)
finally:
t.close()

For earlier versions of Python, you will need to nest the try blocks:

import logging

t=open(filename,'rb')
try:
try:
data=t.read()
#processing data...
except:
logging.exception("Failed to process %r", filename)
finally:
t.close()

Regards,


Vinay Sajip

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


Re: subprocess call acts differently than command line call?

2007-06-07 Thread Rob Wolfe
Jim <[EMAIL PROTECTED]> writes:

> Hello,
>
> I need a program that will traverse a directory tree to ensure that
> there
> are unix-style line endings on every file in that tree that is a text
> file.
> To tell text files from others I want to use the unix "file" command
> (Python's "mimetypes" is not so good for me).  But I am stuck on
> something about getting that output, and I'd greatly appreciate any
> pointers.
>
> Both the command line "file" and the python libmagic binding give the
> same behavior, but I'll illustrate with "file".  It sometimes acts
> differently when run from the command line than when run using
> the subprocess module (with the same user).  For example, it
> sometimes
> gives output when run from the command line but no output when run as
> a subprocess.
>
> Below is a short program to demo.  (I use this on a test file tree
> that is at ftp://joshua.smcvt.edu/pub/hefferon/a.zip if anyone
> is interested.)

[...]

> I've put a transcript of what happens at the bottom of this message.
> One file (in the test tree it is "eqchange.txt") gives no output from
> the above program, but does give an output when I use "file" at the
> command line.

[...]

> -transcript (edited to shorten)
> $ python test.py
> result:  acrotex/readme.txt: ASCII English text, with CRLF line
> terminators
>
> result:  acrotex/eq2db.ins: ASCII English text, with CRLF line
> terminators
>
> result:  acrotex/eqchange.txt:
>
> result:  acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line
> terminators
> result:  acrotex/doc: directory
>
> done
>
> $ file acrotex/eqchange.txt
> acrotex/eqchange.txt: ISO-8859 English text, with CRLF line

That's interesting. I've checked this eqchange.txt file from
your a.zip on my machine and the result is:

$ file acrotex/readme.txt
acrotex/readme.txt: ASCII English text, with CRLF line terminators
$ file acrotex/eqchange.txt
acrotex/eqchange.txt:
$ file acrotex/exerquiz.dtx
acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line terminators

$ file -v
file-4.17
magic file from /etc/magic:/usr/share/file/magic
$ uname -orvm
2.6.18-4-k7 #1 SMP Wed May 9 23:42:01 UTC 2007 i686 GNU/Linux

That's really strange. Have you got only *one* version of ``file``
program on your machine?

-- 
HTH,
Rob
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug/Weak Implementation? popen* routines can't handle simultaneousread/write?

2007-06-07 Thread Terry Reedy

"dmoore" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| alternatives in the standard python distro) Is there some place I can
| submit this as a feature request? (Python dev?)

http://sourceforge.net/tracker/?group_id=5470

But don't hold your breath for a volunteer to respond.  Discussion here is 
good until you have a concrete request and support/rationale.




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


Re: running a random function

2007-06-07 Thread Neil Cerutti
On 2007-06-07, Stebanoid <[EMAIL PROTECTED]> wrote:
> if you have a list of functions you can try this:
>
> import random
> import math
> m[int(math.floor(len(m)*random.random()))]()  # seems like Lisp

Or rather m[random.randint(0, len(m))]()

-- 
Neil Cerutti
Caution: Cape does not enable user to fly. --Kenner's Batman costume
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >