Re: automatically doing some cleaning-up by the process when the systems shuts down

2008-03-19 Thread bharath venkatesh
hi ,
thanks Gabriel ... but  r u sure if it is SYSTERM ?or is it SIGTERM ? I
am not aware of any SYSTERM signal
.. if it is SYSTERM please tell me more about it .. as google search is not
helping ..

and also is there some way for my process which is running as a daemon to
know that system was not shut down properly previously eg a  power
failure .. so that my program can do necessary steps if cleaning up is not
done  during its last termination

On Wed, Mar 19, 2008 at 8:25 AM, Gabriel Genellina <[EMAIL PROTECTED]>
wrote:

> En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh
> <[EMAIL PROTECTED]> escribió:
>
> >   my programs runs as daemon and it does some logging .. when system
> > shuts down .. which may be done manually . i  want my process  do some
> > cleaning up automatically such as writing in to the log file when  the
> > process terminats   before the system shuts down
>
> handling the SYSTERM signal?
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Search the command history - Python Shell

2008-03-19 Thread Sanjaya Vitharana
Hi All,

Are there any simillar key combination in Python Shell like Linux Ctrl+R
(reverse-i-search) to search the command history?

Thanks.

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

Re: automatically doing some cleaning-up by the process when the systems shuts down

2008-03-19 Thread bharath venkatesh
handling SIGTERM allowed me to do cleaning up  while the system shuts down
but as i mentioned previously how can my  process know if the   system was
not shut down properly previously

On Wed, Mar 19, 2008 at 12:36 PM, bharath venkatesh <
[EMAIL PROTECTED]> wrote:

> hi ,
> thanks Gabriel ... but  r u sure if it is SYSTERM ?or is it SIGTERM ?
> I am not aware of any SYSTERM signal
> .. if it is SYSTERM please tell me more about it .. as google search is
> not helping ..
>
> and also is there some way for my process which is running as a daemon to
> know that system was not shut down properly previously eg a  power
> failure .. so that my program can do necessary steps if cleaning up is not
> done  during its last termination
>
> On Wed, Mar 19, 2008 at 8:25 AM, Gabriel Genellina <[EMAIL PROTECTED]>
> wrote:
>
> > En Tue, 18 Mar 2008 09:51:03 -0300, bharath venkatesh
> > <[EMAIL PROTECTED]> escribió:
> >
> > >   my programs runs as daemon and it does some logging .. when
> > system
> > > shuts down .. which may be done manually . i  want my process  do some
> > > cleaning up automatically such as writing in to the log file when  the
> > > process terminats   before the system shuts down
> >
> > handling the SYSTERM signal?
> >
> > --
> > Gabriel Genellina
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Using threads in python is safe ?

2008-03-19 Thread Deepak Rokade
Thanks all for removing confusion about GIL,
one more question;
If jobs to be processed by threds is I/O bound would multithreading help
python to improve speed of application ?

Since I read that " multithreading is not a good strategy to improve speed
of python application."


On Mon, Mar 17, 2008 at 7:00 AM, Benjamin <[EMAIL PROTECTED]>
wrote:

> On Mar 16, 3:40 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
> > En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade <[EMAIL PROTECTED]>
> > escribi�:
> >
> > > I want to use therads in my application. Going through the docs , I
> read
> > > about GIL.
> > > Now I am confused whether using threads in python is safe or not.
> >
> > > One thing I know that if I am accessing global variables in two or
> more
> > > threads I need to synchronize them
> > > using locking or such mechanism so that only one thread access them at
> a
> > > time.
> >
> > Yes, altough some operations are known to be atomic so you don't need a
> > lock in that cases. I think there is a list in the wiki somewhere
> http://wiki.python.org/moinor perhaps at the effbot's site
> http://www.effbot.org
> Even for atomic operations, you should lock, though. That is not
> consistent over different Python implementations and is not always
> going to be in same in CPython.
> >
> > > 1.  In order to support multi-threaded Python programs, there's a
> global
> > > lock that must be held
> > > by the current thread before it can safely access Python objects.
> > > Does this lock need to be held by python application script
> expliciltly
> > > before accessing any python object or
> > > interpreter takes acre of it ?
> >
> > No, the interpreter takes care of it. The GIL is a concern for those
> > writing extensions using the Python API.
> >
> > > 2. Does multithreaded python script need to held lock before calling
> any
> > > blocking I/O call?
> > > Or one should not worry about GIL while using python threads if job to
> be
> > > processed by thread does not call
> > > any global variables and thread unsafe Python/C extension ?
> >
> > Python code should not worry about the GIL. The problem would be, a
> > callback written in Python for a not-thread-aware extension that had
> > released the GIL.
> >
> > --
> > Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Thanx & Regards,
Deepak Rokade

Do what u Enjoy &
Enjoy what u Do...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is there a way to get __thismodule__?

2008-03-19 Thread Ben Hoyt
Aha! Thanks, Jeff. I'd heard about metaclasses, but never really seen them
used. Your example was very helpful.

This is somewhere that I would personally use a metaclass. That way,
> if you define more subclasses of Message, you're not limited to doing
> so in that single module.
>

Cheers,
Ben.


-- 
Ben Hoyt, http://benhoyt.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: placing a Python com object into Excel

2008-03-19 Thread Tim Roberts
Mathew <[EMAIL PROTECTED]> wrote:

>Thanks for the tip. But, instead of an AddIn, what if I want to be able 
>to insert an object? I see that the demo adds items to the windows 
>registry under \Excel\AddIns. Is there a similar location for the 
>"Insert Object" command?

What you see there is the list of registered ActiveX controls.  You need to
implement a few additional interfaces.  I believe IOleInPlaceObject is
required to satisfy Excel.

http://msdn2.microsoft.com/en-us/library/aa751972.aspx
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stdout custom

2008-03-19 Thread castironpi
> >> > Can I allocate a second console window, so I can place certain output
> >> > to that directly, and leave the original streams alone?  I tried
> >> Have you tried using the creationflags argument to subprocess.Popen?
> >> Specially the CREATE_NEW_CONSOLE flag. See the Microsoft documentation
> >> for CreateProcess  
> >> athttp://msdn2.microsoft.com/en-us/library/ms682425(VS.85).aspx
> >> (Note that a process can be attached at most to one console)
>
> > One console per process is fine, but I tried using 'cmd.exe',
> > 'cmd.exe /K', and 'more.com' (fully specified in c/windows/system32)
> > as separate processes.  The sign is the console window splashes up and
> > vanishes right away.
>
> Apparently you have to either redirect stdout AND stdin, or none of them.  
> This worked for me:
>
> p = subprocess.Popen('c:\\windows\\system32\\cmd.exe',
>          stdout=subprocess.PIPE, stdin=subprocess.PIPE,
>          creationflags=subprocess.CREATE_NEW_CONSOLE)
> p.communicate("dir\n")

This worked for me.

import subprocess
p = subprocess.Popen('c:\\windows\\system32\\cmd.exe',
 stdout=subprocess.PIPE, stdin=subprocess.PIPE,
 creationflags=subprocess.CREATE_NEW_CONSOLE)

import time
import threading
def th():
while 1:
time.sleep( .01 )
s= p.stdout.read(1)
print( ':', end= '' )
if not s: continue
print( s.decode(), end= '' )


import thread
thread.start_new_thread( th, () )
time.sleep( 2 )
p.stdin.write( b'c:\\windows\\system32\\more.com\n' )
p.stdin.flush()
print ( 'abc' )
while 1:
time.sleep( 1 )
p.stdin.write( b'abc\n' )
p.stdin.flush()
print ( 'abc' )
p.wait()
time.sleep( 10 )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parsing json output

2008-03-19 Thread Tim Roberts
Gowri <[EMAIL PROTECTED]> wrote:
>
>I have a service running somewhere which gives me JSON data. 
>...
>This prints a whole bunch of nonsense as expected.

It's not nonsense.  It's JSON.

>I use cjson and am
>unable to figure out how to print this json response

You are already printing the JSON response.  That's what that script does.

>and I guess if I
>can do this, parsing should be straightforward? doing a
>cjson.decode(str(repsonse)) does not work.

If response.read() returns the JSON string, as you show above, one might
expect 
cjson.decode(response.read())
to parse it.  Have you read the cjson documentation?
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to solve a three-element equation set?

2008-03-19 Thread Gerhard Häring
purple wrote:
> Could you guys do me a favor for solving a equation set?
> 
> Z=d/4*(1-SIN(X)/X)
> X=8q/(D^2*Y)+SIN(X)
> Y=1/n*Z^(2/3)*i^(1/2)
> 
> In this equation set, X,Y&Z are the unkown parameters, the others say,
> d, q, n&i are known. SO in python, how to program it to represent X, Y
> and Z in the form of d, q, n and i?

Will you do your homework yourself, please?

Hint: make X, Y and Z Python functions.

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


How to solve a three-element equation set?

2008-03-19 Thread purple
Could you guys do me a favor for solving a equation set?

Z=d/4*(1-SIN(X)/X)
X=8q/(D^2*Y)+SIN(X)
Y=1/n*Z^(2/3)*i^(1/2)

In this equation set, X,Y&Z are the unkown parameters, the others say,
d, q, n&i are known. SO in python, how to program it to represent X, Y
and Z in the form of d, q, n and i?

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


PODCasts

2008-03-19 Thread Mike D
I really should say net cast as I think it's a better term ;)

Does anyone have any recommended net casts on Python, or programming in
general?

Whats everyone listening to?

Cheers Guys!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Decode email subjects into unicode

2008-03-19 Thread Gertjan Klein
Laszlo Nagy wrote:

>However, there are malformed emails and I have to put them into the 
>database. What should I do with this:
[...]
>There is no encoding given in the subject but it contains 0x92. When I 
>try to insert this into the database, I get:

This is indeed malformed email. The content type in the header specifies
iso-8859-1, but this looks like Windows code page 1252, where character
\x92 is a single right quote character (unicode \x2019).

As the majority of the mail clients out there are Windows-based, and as
far as I can tell many of them get the encoding wrong, I'd simply try to
decode as CP1252 on error, especially if the content-type claims
iso-8859-1. Many Windows mail clients consider iso-8859-1 equivalent to
1252 (it's not; the former doesn't use code points in the range \x8n and
\x9n, the latter does.)

Regards,
Gertjan.

-- 
Gertjan Klein <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lock access to serial port

2008-03-19 Thread taco
[EMAIL PROTECTED] wrote:

> hello group,
> 
> how to get ttyS0 serial port for exclusive access? I have a python
> script that uses this device with AT commands. I need that two
> instances can call simultaneosuly this python script but only one of
> them gets the device. I tried fcntl.flock, it was just ignored, put
> writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not
> know what are appropriate arguments), googled half a day for various
> phrases, error messages etcwithout success.
> 
> please help,
> 
> Andra
not sure if I understand you well, but how about a server application which
accepts 2 clients which can send messages which are output on the serial
device? The serial device access protected with a mutex while receiving
messages done in 2 threads or something.
taco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is hash map data structure available in Python?

2008-03-19 Thread Diez B. Roggisch
grbgooglefan schrieb:
> Hi,
> I have a situation that I need to search a name in a big list of names
> in my Python embedded interpreter. I am planning to use hash map for
> quicker search.
> How do I create hash map in Python?
> Can you please guide me to some documentation or tutorial which
> provides information on creating, editing, searching through hash map
> in Python?

http://docs.python.org/tut/node7.html#SECTION00750

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


Re: method to create class property

2008-03-19 Thread Diez B. Roggisch
> Isn't that::
> 
> 
> 
>  @propset(foo)
> 
>  def foo(self, value):
> 
>  self._value = value

Yeah, you are right.

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


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread Gerhard Häring
wesley chun wrote:
> http://it.slashdot.org/it/08/03/18/1633229.shtml
> 
> it was surprising and disappointing that Python was not mentioned
> *anywhere* in that article [...]

Probably because Ruby is all hot and sexy nowadays ;-) Though it's 
remarkably close to Python, apparently. So close that I couldn't be 
bothered to learn it.

In fact, for me personally, Python was about the last programming 
language I learnt out of intrinsic motivation. I tried to take a look at 
functional langugages like Haskell and Erlang, but I tend to quickly get 
bored of toy examples and can learn best if I can apply a new language 
to a real problem that it can solve better than the other languages I 
know. Haven't found that killer problem so far ...

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


is hash map data structure available in Python?

2008-03-19 Thread grbgooglefan
Hi,
I have a situation that I need to search a name in a big list of names
in my Python embedded interpreter. I am planning to use hash map for
quicker search.
How do I create hash map in Python?
Can you please guide me to some documentation or tutorial which
provides information on creating, editing, searching through hash map
in Python?
Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread Paul Rubin
Gerhard Häring <[EMAIL PROTECTED]> writes:
> Probably because Ruby is all hot and sexy nowadays ;-) Though it's
> remarkably close to Python, apparently. So close that I couldn't be
> bothered to learn it.

Ruby is apparently more Smalltalk-like and some consider it cleaner
than Python.  Like you, I figure it's close enough to Python that
I haven't bothered with it.  

> In fact, for me personally, Python was about the last programming
> language I learnt out of intrinsic motivation. I tried to take a look
> at functional langugages like Haskell and Erlang, but I tend to
> quickly get bored of toy examples and can learn best if I can apply a
> new language to a real problem that it can solve better than the other
> languages I know. Haven't found that killer problem so far ...

The killer problem for Erlang is highly concurrent, distributed
systems.  I've been wanting to read Joe Armstrong's book about it
since I have some interest in that sort of thing.  It's not simply the
ability to run vast numbers of threads and automatically marshal data
between them (even if they're on separate computers), but also its
convenient management of software faults through "supervision trees".
In most languages we normally program our functions to notice error
conditions and recover from them, raise exceptions that are handled
elsewhere in the app, etc.  In Erlang you just let the thread crash,
and have the supervision system deal with restarting it, logging the
error, etc.  This separation of concerns apparently helps reliability
of nonstop services like phone switches considerably.  Also, Erlang
has hot-patching facilities so you can upgrade your program while it's
running, with 10,000 active network connections staying up and nobody
outside noticing that anything has changed.

Re Haskell: I've been spending a lot of time on Haskell recently,
though I haven't done anything nontrivial with it yet (just some small
stuff).  But I think it's better for complex program development than
Python is, and even small Haskell programs, (while they are more
difficult to write, at least at my present level of experience) seem
both cleaner and more solid in terms of confidence of correctness than
the corresponding Python programs.  Also, Haskell code runs a lot
faster than Python code (real native-code compiler that can use
multicore hardware), and there is a clever automatic unit testing
system (QuickCheck) that relies on Haskell's static type system to
generate random tests automatically.  On the other hand, Python's
standard libraries do more stuff and are better packaged.  It's
certainly easier to do lightweight internet scripting in Python.  If I
were writing something like a compiler, I'd probably use Haskell.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get actual call signature?

2008-03-19 Thread Hans Georg Krauthäuser
On 18 Mrz., 11:40, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
> Say, I have a function defined as:
>
> def fun(arg_one, arg_two='x', arg_three=None):
> pass
>
> Is there any way to get actual arguments that will be effectively used
> when I call this function in various ways, like:
>
> fun(5) => [5, 'x', None]
> fun(5, arg_three=['a', 'b']) => [5, 'x', ['a', 'b']]
> fun(5, 'something') => [5, 'something', None]
>
> (et caetera, using all possible mixes of positional, keyword and default
> arguments)
>
> I'd like to wrap function definition with a decorator that intercepts
> not only passed arguments, but also defaults that will be actually used
> in execution.
>
> If this sounds not feasible (or is simply impossible), I'll happily
> throw this idea and look for another one. ;)
>
> --
> Jarek Zgoda
> Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101
>
> "We read Knuth so you don't have to." (Tim Peters)

Perhaps like so:

import inspect

class CLS(object):
def fun(self, arg_one, arg_two='x', arg_three=None):
print get_signature(self)

def get_signature(obj):
frame = inspect.currentframe()
outerframes = inspect.getouterframes(frame)
caller = outerframes[1][0]
try:
args, varargs, varkw, loc = inspect.getargvalues(caller)
allargs = args
allargs.pop(0) # self
if not varargs is None:
allargs += varargs
if not varkw is None:
allargs += varkw
sdict={}
for arg in allargs:
sdict[arg]=caller.f_locals[arg]
ccframe = outerframes[2][0]
ccmodule = inspect.getmodule(ccframe)
try:
slines, start = inspect.getsourcelines(ccmodule)
except:
clen = 100
else:
clen = len(slines)
finfo = inspect.getframeinfo(ccframe, clen)
theindex = finfo[4]
lines = finfo[3]
theline = lines[theindex]
cmd = theline
for i in range(theindex-1, 0, -1):
line = lines[i]
try:
compile (cmd.lstrip(), '', 'exec')
except SyntaxError:
cmd = line + cmd
else:
break
finally:
del frame
del outerframes
del caller
del ccframe

return cmd, sdict

if __name__ == '__main__':
c=CLS()
c.fun(5)
c.fun(5, arg_three=['a', 'b'])
c.fun(5, 'something')
c.fun(5,
'something')

a=c.fun

a(4)

Best Regards

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


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread Torsten Bronger
Hallöchen!

Paul Rubin writes:

> [...]
>
> Re Haskell: I've been spending a lot of time on Haskell recently,
> though I haven't done anything nontrivial with it yet (just some
> small stuff).  But I think it's better for complex program
> development than Python is,

Could you elaborate on this?  (Sincere question; I have almost no
idea of Haskell.)

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftp recursively

2008-03-19 Thread Paul Rubin
Jeff Schwab <[EMAIL PROTECTED]> writes:
> ftping it as a flat file, and untarring it on the other side.  Of
> course, the motivation wasn't just to get the files from point A to
> point B using Unix (which I already know how to do), but to take
> advantage of an opportunity to learn some Python; next time, I'll try
> the ftpmirror.py script if it's generic enough, or ftplib if there are
> more specific requirements.

I see, that wasn't clear in your original post.  You should look at
the os.walk function if you want to know how to traverse a directory
tree (maybe you are already doing this).  Also, for security reasons,
it's getting somewhat uncommon, and is generally not a good idea to
run an ftpd these days, even on a LAN.  It's more usual these days
to transfer all files by rcp or rsync tunnelled through ssh.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread Paul Rubin
Torsten Bronger <[EMAIL PROTECTED]> writes:
> > Re Haskell: I've been spending a lot of time on Haskell recently,
> > though I haven't done anything nontrivial with it yet (just some
> > small stuff).  But I think it's better for complex program
> > development than Python is,
> 
> Could you elaborate on this?  (Sincere question; I have almost no
> idea of Haskell.)

http://wiki.python.org/moin/PythonVsHaskell is a fairly high-level
comparison.

I think it's easier to write complex code in Haskell because:

  1) it has a powerful static type system that lets you express
important invariants and have them enforced at compile time.  This not
only catches errors but helps you understand the program logic almost
like running the code under a debugger does.  If you try to fill a gap
by putting in a piece of the wrong shape, it just won't fit and the
compiler will tell you what you really wanted.  On the other hand,
most types are inferred by the compiler, so you don't need a lot of
cumbersome declarations like in Java.

  2) The basic list type in Haskell works something like Python
iterators, but they don't change state when you consume an item.  In
fact all Haskell data is immutable.  You avoid vast classes of bugs
this way.  But you do have to change the way you think about
programming.

I may write a longer comparison post sometime later.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to get __thismodule__?

2008-03-19 Thread Peter Otten
benhoyt wrote:

> Is there a way to get __thismodule__ in Python? That is, the current
> module you're in. Or isn't that known until the end of the module?
> 
> For instance, if I'm writing a module of message types/classes, like
> so:
> 
> class SetupMessage(Message):
> number = 1
> 
> class ResetMessage(Message):
> number = 2
> 
> class OtherMessage(Message):
> number = 255
> 
> nmap = {  # maps message numbers to message classes
> 1: SetupMessage,
> 2: ResetMessage,
> 255: OtherMessage,
> }
> 
> Or something similar. But adding each message class manually to the
> dict at the end feels like repeating myself, and is error-prone. It'd
> be nice if I could just create the dict automatically, something like
> so:
> 
> nmap = {}
> for name in dir(__thismodule__):
> attr = getattr(__thismodule__, name)
> if isinstance(attr, Message):
> nmap[attr.number] = attr
> 
> Or something similar. Any ideas?

Use globals():

def is_true_subclass(a, b):
try:
return issubclass(a, b) and a is not b
except TypeError:
return False

nmap = dict((m.number, m) for m in globals().itervalues()
if is_true_subclass(m, Message))
print nmap

You may also rely on duck-typing, assuming that everything that has a number
attribute is a Message subclass:

nmap = dict((m.number, m) for m in globals().itervalues()
if hasattr(m, "number"))

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


Re: Need Help Starting Out

2008-03-19 Thread Bruno Desthuilliers
jmDesktop a écrit :
> Hi, I would like to start using Python, but am unsure where to begin.
> I know how to look up a tutorial and learn the language, but not what
> all technologies to use.  I saw references to plain Python, Django,
> and other things.
> 
> I want to use it for web building with database access.  What do I use
> for that?  Does it matter what I use on the client side (mootools, or
> whatever)?

Your best bets are probably Django, Pylons or web.py. But you should 
learn enough of the core language itself before jumping in web stuff IMHO.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: keyboard "interrupt"

2008-03-19 Thread Hans Georg Krauthäuser
On 18 Mrz., 22:18, [EMAIL PROTECTED] (John Fisher) wrote:
> Hi Group,
>
> I have been absent a while, mainly because I have been getting better at
> figuring out my own Python problems. But not this one...
>
> I have a timed loop performing certain tasks until a total period of
> time has elapsed. I would like to be able to interrupt the loop or set
> various flags during execution via keyboard input. raw_input seems to
> just stop everything cold. I want the ability to just sacn the keyboard
> buffer and see if something is there, then proceed normally in the loop
> if there is no input in the buffer. Make sense? Totally easy? Let me
> know...
>
> wave_man

I use this code:

class _Getch:
"""Gets a single character from standard input.  Does not echo to
the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
try:
self.impl = _GetchUnix()
except ImportError:
self.impl = _GetchMacCarbon()

def __call__(self): return self.impl()


class _GetchUnix:
def __init__(self):
import tty, sys, termios # import termios now or else you'll
get the Unix version on the Mac

def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

class _GetchWindows:
def __init__(self):
import msvcrt

def __call__(self):
import msvcrt
return getch()


class _GetchMacCarbon:
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned.  The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
def __init__(self):
import Carbon

def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the
keyDownMask
return ''
else:
#
# The event contains the following info:
# (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)
[1]
#
# The message (msg) contains the ASCII char which is
# extracted with the 0x00FF charCodeMask; this
# number is converted to an ASCII character with chr()
and
# returned
#
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)
[1]

return chr(msg & 0x00FF)

Best regards
Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PODCasts

2008-03-19 Thread Tim Chase
> I really should say net cast as I think it's a better term ;)
> 
> Does anyone have any recommended net casts on Python, or programming in
> general?

Well, though it's been a while since I last noticed a new release 
(last one dated Dec '07), the archives of "Python 411" should all 
be online:

   http://www.awaretek.com/python/

-tkc



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


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread Torsten Bronger
Hallöchen!

wesley chun writes:

> http://it.slashdot.org/it/08/03/18/1633229.shtml
>
> it was surprising and disappointing that Python was not mentioned
> *anywhere* in that article but when someone replied, it sparked a
> long thread of post-discussion.

Well, not because I like Python so much, but I find this blog entry
highly unoriginal.  Browsing through Wikipedia gives more
insight ...

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decode email subjects into unicode

2008-03-19 Thread Laszlo Nagy
Gertjan Klein wrote:
> Laszlo Nagy wrote:
>
>   
>> However, there are malformed emails and I have to put them into the 
>> database. What should I do with this:
>> 
> [...]
>   
>> There is no encoding given in the subject but it contains 0x92. When I 
>> try to insert this into the database, I get:
>> 
>
> This is indeed malformed email. The content type in the header specifies
> iso-8859-1, but this looks like Windows code page 1252, where character
> \x92 is a single right quote character (unicode \x2019).
>
> As the majority of the mail clients out there are Windows-based, and as
> far as I can tell many of them get the encoding wrong, I'd simply try to
> decode as CP1252 on error, especially if the content-type claims
> iso-8859-1. Many Windows mail clients consider iso-8859-1 equivalent to
> 1252 (it's not; the former doesn't use code points in the range \x8n and
> \x9n, the latter does.)
>
>   
Thank you very much!

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


Re: Interesting math problem

2008-03-19 Thread BJörn Lindqvist
On Mon, Mar 17, 2008 at 11:57 PM, Arnaud Delobelle
<[EMAIL PROTECTED]> wrote:
>  > def make_slope(distance, parts):
>  > step = distance / float(parts)
>  > intstep = int(step)
>  > floatstep = step - intstep
>  >
>  > steps = []
>  > acc = 0.0
>  > for i in range(parts):
>  > acc += floatstep
>  > step = intstep
>  > if acc > 0.999:
>  > step += 1
>  > acc -= 1.0
>  > steps.append(step)
>  > return steps
>
>  OK then, using list comprehensions.  It is more succint, is it easier
>  to read?
>
>  def slope(dist, parts):
> return [(i+1)*dist/parts - i*dist/parts for i in xrange(parts)]

Congratulations! You Won! Jeff Schwab's recursive approach is also
cool but this is the most interesting abuse of integer division I have
seen. I don't think any of the variants are readable at a first
glance, but with a comment it should be ok.


-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


PSF Community Awards

2008-03-19 Thread Steve Holden
For those who weren't at PyCon, or who missed the announcement (which 
seems to include all of the recipients :-) I have just made a post in 
the PSF blog to publicize the first PSF Community Awards. See

   http://pyfound.blogspot.com/2008/03/psf-community-awards.html

These awards are made to recognize those who perform work of benefit to 
the broader Python community.

If you have benefited from the work the first award winners have done, 
please further acknowledge their valuable contributions by adding a 
short comment to the post.

Steve Holden
Chairman, Python Software Foundation

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


Re: Is there a way to get __thismodule__?

2008-03-19 Thread Duncan Booth
benhoyt <[EMAIL PROTECTED]> wrote:

> But adding each message class manually to the
> dict at the end feels like repeating myself, and is error-prone. It'd
> be nice if I could just create the dict automatically, something like
> so:
> 
> nmap = {}
> for name in dir(__thismodule__):
> attr = getattr(__thismodule__, name)
> if isinstance(attr, Message):
> nmap[attr.number] = attr
> 
> Or something similar. Any ideas?
> 
> (A friend suggested class decorators, which is a good idea, except
> that they're not here until Python 2.6 or Python 3000.)
> 

Why not just use your base class?

class Message(object):
@staticmethod
def getmap():
return dict((cls.number, cls)
for cls in Message.__subclasses__())

class SetupMessage(Message):
number = 1

class ResetMessage(Message):
number = 2

class OtherMessage(Message):
number = 255

nmap = Message.getmap()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lists v. tuples

2008-03-19 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> I am puzzled by the failure on 'a in a' for a=[a].  >>> a== [a] also
> fails.  Can we assume/surmise/deduce/infer it's intentional?
> 
It may be less confusing if instead of an assignment following by a test 
you just consider doing the test at the same time as the assignment 
(then again it changes the behaviour so it may just be more confusing).

There is a very limited set of values for which you would expect this 
output:

>>> a==[a]
True
>>> a in [a]
True

The most obvious one is a simple recursive list:

>>> a = []
>>> a.append(a)
>>> a==[a]; a in [a]
True
True

Pushing the recursion down a level breaks some of the comparisons:

>>> a = [[]]
>>> a[0].append(a)
>>> a==[a]
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: maximum recursion depth exceeded in cmp
>>> a in [a]
True
>>> a in a
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: maximum recursion depth exceeded in cmp

which may be considered a bug or possibly it is just a limit of the 
implementation.

This also produces an overflow (in fact I think it is just the same 
situation as above, recursing on the same list is handled, recursing on 
different but equivalent lists is not):

>>> a = []; a.append(a)
>>> b = []; b.append(b)
>>> a==b
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: maximum recursion depth exceeded in cmp

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


Re: Search the command history - Python Shell

2008-03-19 Thread Tim Chase
> Are there any simillar key combination in Python Shell like Linux Ctrl+R
> (reverse-i-search) to search the command history?


It must depend on how your version of Python was built...mine 
here on my Linux box has exactly that functionality.  I press ^R 
and start typing, and the line comes up from my typed history.

bash$ python2.4
Python 2.4.4 (#2, Jan  3 2008, 13:36:28)
[GCC 4.2.3 20071123 (prerelease) (Debian 4.2.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> a = 42
(reverse-i-search)`a': a = 42


bash$ python2.5
Python 2.5.2a0 (r251:54863, Feb 10 2008, 01:31:28)
[GCC 4.2.3 (Debian 4.2.3-1)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> a = 42
(reverse-i-search)`a': a = 42


-tkc


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


RE: First Program Bug (Newbie)

2008-03-19 Thread Andreas Tawn
[snip]
>> What is the square root function in python?
>
> There's one in the math module. Use the one in gmpy if you have it.

Or raise to the power 1/power

>>> 9**(1.0/2)
3.0

Also works for cube root, quad root etc.

>>> 27**(1.0/3)
3.0

>>> 81**(1.0/4)
3.0

>>> 243**(1.0/5)
3.0

Cheers,

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


Re: Huge problem gettng MySQLdb to work on my mac mini running Macosx 10.5 Leopard

2008-03-19 Thread geert
On Mar 19, 2:26 am, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On Mar 19, 9:47 am, geert <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Mar 18, 6:56 pm, geert <[EMAIL PROTECTED]> wrote:
>
> > > On Mar 14, 1:15 pm, [EMAIL PROTECTED] wrote:
>
> > > > look 
> > > > athttp://groups.google.be/group/comp.lang.python/browse_thread/thread/d...
>
> > > > There is a macpython list that you can consult 
> > > > athttp://www.nabble.com/Python---pythonmac-sig-f2970.html
>
> > > Just wanted to let you know that I've solved my problem. The solution
> > > is to compile mysql using
>
> > > MACOSX_DEPLOYMENT_TARGET=10.5 \
> > > CFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
> > > LDFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
> > > CXXFLAGS='-arch i386 -arch x86_64 -arch ppc7400 -arch ppc64' \
> > > ./configure --disable-dependency-tracking  --enable-thread-safe-client
> > > --prefix=/usr/local/mysql
>
> > > You then go this way to get it running on your machine:
>
> > >http://hivelogic.com/articles/installing-mysql-on-mac-os-x/
>
> > > Then reinstall MySQLdb. Magic!
>
> > > Geert
>
> > Seems that I've yelled success to quickly. Everything's ok as long as
> > I just run the django dev server, but moving to apache 
> > throughmod_wsgibrings a well-known but less than comforting complaint:
>
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]mod_wsgi(pid=2352):
> > Exception occurred processing WSGI script '/Users/geert/Sites/LithoNET/
> > LN/LNApache.wsgi'., referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1] Traceback (most recent
> > call last):, referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/core/handlers/wsgi.py", line 205, in
> > __call__, referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     response =
> > self.get_response(request), referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/core/handlers/base.py", line 64, in
> > get_response, referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     response =
> > middleware_method(request), referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/contrib/sessions/middleware.py", line
> > 13, in process_request, referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     engine =
> > __import__(settings.SESSION_ENGINE, {}, {}, ['']), 
> > referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/contrib/sessions/backends/db.py", line
> > 2, in , referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     from
> > django.contrib.sessions.models import Session, 
> > referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/contrib/sessions/models.py", line 5,
> > in , referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     from django.db
> > import models, referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/db/__init__.py", line 17, in ,
> > referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     backend =
> > __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {},
> > {}, ['']), referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]   File "/Library/
> > Python/2.5/site-packages/django/db/backends/mysql/base.py", line 12,
> > in , referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1]     raise
> > ImproperlyConfigured("Error loading MySQLdb module: %s" % e), 
> > referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1] ImproperlyConfigured:
> > Error loading MySQLdb module: dlopen(/Library/WebServer/.python-eggs/
> > MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-tmp/_mysql.so, 2): no
> > suitable image found.  Did find:, referer:http://localhost/images/
> > [Tue Mar 18 23:34:25 2008] [error] [client ::1] \t/Library/
> > WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-macosx-10.5-i386.egg-
> > tmp/_mysql.so: no matching architecture in universal wrapper, 
> > referer:http://localhost/images/
>
> Did you again confirm that running:
>
>   file /Library/WebServer/.python-eggs/MySQL_python-1.2.2-py2.5-
> macosx-10.5-i386.egg-tmp/_mysql.so
>
> shows the .so having the required architectures, specifically what
> Apache runs as (eg. x86_64)?
>
> Do the gcc compiler flags when building and linking the .so file show
> all the architecture flags?
>
> Have you empty the Python egg cache to make sure it isn't an older
> compiled version?
>
> 

Re: lock access to serial port

2008-03-19 Thread [EMAIL PROTECTED]
not the goal setup but the way I tried it out - a webpage to send an
sms to mobile phone. This is an php what calls a python script. A
python script opens serial device, checks for gsm network, sends a
message - on all the way I try to make sure that appropriate answers
are received from the gsm device so that I know that all is going well
(and if not - cancel it with error message).

Testing it with sending an sms from two open webpages, I normally got
that one message was sent and for the other I received "try once more,
happened that and that". But I got also an inadmissible situation -
the received sms contained also unwanted text. As far as I can realize
how to deal with it is not allowing writing to the device for two
processes simultaneously.


Andra


On 19 Marts, 11:00, taco <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > hello group,
>
> > how to get ttyS0 serial port for exclusive access? I have a python
> > script that uses this device with AT commands. I need that two
> > instances can call simultaneosuly this python script but only one of
> > them gets the device. I tried fcntl.flock, it was just ignored, put
> > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not
> > know what are appropriate arguments), googled half a day for various
> > phrases, error messages etcwithout success.
>
> > please help,
>
> > Andra
>
> not sure if I understand you well, but how about a server application which
> accepts 2 clients which can send messages which are output on the serial
> device? The serial device access protected with a mutex while receiving
> messages done in 2 threads or something.
> taco
-- 
http://mail.python.org/mailman/listinfo/python-list


a beginner, beginners question

2008-03-19 Thread klaus
Hello,

I'm trying to learn python programming and so far so good. However when 
trying to master the oop side I ran into a small problem.

I think I've done everything ok as outlined below. But I just don't 
understand why the `method' of `class' example isn't printing any of the 
variables that I have set earlier on ? Could someone please explain to me 
what it is I am doing wrong ? 

Thank you so much !

#!/usr/bin/env python

class example:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar

def method(self):
print "method ... :" 
print self.foo
print self.bar


if __name__ == "__main__":
obj = example 
obj.foo = "var1"
obj.bar = "var2"
obj.method
-- 
http://mail.python.org/mailman/listinfo/python-list


Script Request...

2008-03-19 Thread some one
Hi all, I am not to familiar with python yet and I am wondering if 
someone can write a script that will monitor my DSL modems IP address 
and notify when it changes, its a 2Wire Advanced DSL Modem.  I need to 
know when it changes because I am trying to run my own inhouse server 
and have to update my domain records through verio.com.

The script would need to read the text of a web page( on my modem the 
address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and 
search for a string containing the IP address.

Can anyone help?
thanks, I'll keep monitoring this thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a beginner, beginners question

2008-03-19 Thread Tim Chase
> class example:
> def __init__(self, foo, bar):
> self.foo = foo
> self.bar = bar
> 
> def method(self):
> print "method ... :" 
> print self.foo
> print self.bar
> 
> if __name__ == "__main__":
> obj = example 

This makes "obj" a synonym for "example".  You want to 
instantiate your "example" class with

   obj = example("Some foo", "Some Bar")

> obj.foo = "var1"
> obj.bar = "var2"

which then makes these two lines either unneeded or an 
overwriting of the initialization

> obj.method

and this returns a function, not the results of the function. 
You need to call it

   obj.method()

-tkc




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


Re: a beginner, beginners question

2008-03-19 Thread John Machin
On Mar 19, 9:40 pm, klaus <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm trying to learn python programming and so far so good. However when
> trying to master the oop side I ran into a small problem.
>
> I think I've done everything ok as outlined below. But I just don't
> understand why the `method' of `class' example isn't printing any of the
> variables that I have set earlier on ? Could someone please explain to me
> what it is I am doing wrong ?
>
> Thank you so much !
>
> #!/usr/bin/env python
>
> class example:

What book or online tutorial are using that doesn't lead you to
express that as:
class Example(object):
??


> def __init__(self, foo, bar):
> self.foo = foo
> self.bar = bar
>
> def method(self):
> print "method ... :"
> print self.foo
> print self.bar
>
> if __name__ == "__main__":
> obj = example
To see what is happening here, do:
print repr(obj)
You need to CALL the class:
obj = example()

> obj.foo = "var1"
> obj.bar = "var2"
> obj.method
This expression produces the method itself, then throws it away.
You need to CALL the method:
   obj.method()

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


Re: PyCon Feedback and Volunteers (Re: Pycon disappointment)

2008-03-19 Thread NickC
On Mar 19, 6:07 am, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> As I have never attended PyCon, the amount of entertainment already
> gleaned from this thread has wildly exceeded my expectations. :)  Are
> slides or notes from any of the presentations available online?  What
> was the topic of the well-received presentation from Google?

I'm mostly intrigued by the tantalising hints being dropped regarding
Steve Holden's Teach Me Twisted talk ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


printing dictionary and tuple

2008-03-19 Thread Beema shafreen
Hi everbody

i am trying to print the dictionary values and tuple in a same line as below

print "\t".join(dict[a].values())+'\t'+"\t".join(b)

Error I get is the  TypeError,
 since i have  misisng values in the dictionary. if i use exception i will
miss those
how should i print the data without missing the lines excluding the error
separated by tab.


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

Re: a beginner, beginners question

2008-03-19 Thread klaus
On Wed, 19 Mar 2008 05:57:04 -0500, Tim Chase wrote:

>> class example:
>> def __init__(self, foo, bar):
>> self.foo = foo
>> self.bar = bar
>> 
>> def method(self):
>> print "method ... :"
>> print self.foo
>> print self.bar
>> 
>> if __name__ == "__main__":
>> obj = example
> 
> This makes "obj" a synonym for "example".  You want to instantiate your
> "example" class with
> 
>obj = example("Some foo", "Some Bar")
> 
>> obj.foo = "var1"
>> obj.bar = "var2"
> 
> which then makes these two lines either unneeded or an overwriting of
> the initialization
> 
>> obj.method
> 
> and this returns a function, not the results of the function. You need
> to call it
> 
>obj.method()
> 
> -tkc

Ok thank you for elaborating I think I've got it.

Thnkx. !

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


xml sax

2008-03-19 Thread Timothy Wu
Hi,

I am using  xml.sax.handler.ContentHandler to parse some simple xml.

I want to detect be able to parse the content of this tag embedded in the
XML.

174

Is the proper way of doing so involving finding the "Id" tag
from startElement(), setting flag when seeing one, and in characters(),
when seeing that flag set, save the content?

What if multiple tags of the same name are nested at different levels
and I want to differentiate them? I would be setting a flag for each level.
I can imagine things get pretty messy when flags are all around.

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

Re: Script Request...

2008-03-19 Thread Diez B. Roggisch
some one wrote:

> Hi all, I am not to familiar with python yet and I am wondering if
> someone can write a script that will monitor my DSL modems IP address
> and notify when it changes, its a 2Wire Advanced DSL Modem.  I need to
> know when it changes because I am trying to run my own inhouse server
> and have to update my domain records through verio.com.
> 
> The script would need to read the text of a web page( on my modem the
> address is http://192.168.0.1/xslt?PAGE=B01&THISPAGE=&NEXTPAGE=B01 ) and
> search for a string containing the IP address.
> 
> Can anyone help?
> thanks, I'll keep monitoring this thread.

Try urllib2 to fetch the data, use either string-search, regular expressions
or even BeautifulSoup to extract the data. Use a cron-job to do that on a
regular base or use module time.sleep() together with an endless loop to
monitor that location periodically.

Show us your concrete efforts, and we will suggest improvements.

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


Re: PODCasts

2008-03-19 Thread Simon Brunning
On Wed, Mar 19, 2008 at 9:06 AM, Mike D <[EMAIL PROTECTED]> wrote:
> I really should say net cast as I think it's a better term ;)

Since I'm working at The Guardian, I'm bound to stand up for the term
'podcast'. ;-) Besides, it's very established now - too late to fight
it.

> Does anyone have any recommended net casts on Python, or programming in
> general?
>
> Whats everyone listening to?

Python411: 
This Week in Django: 

Plus a bunch of non-Python related stuff.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.getsize() on Windows

2008-03-19 Thread Steven D'Aprano
On Tue, 18 Mar 2008 13:58:33 -0700, Sean DiZazzo wrote:

> I'm seeing some behavior that is confusing me.  I often use a simple
> function to tell if a file is growing...ie being copied into a certain
> location.  (Can't process it until it's complete)

Surely though, under Windows, while something else is writing to the file 
you can't open it? So instead of this:


def wait_for_open(pathname):
"""Return file open for reading, or fail. 
If the file is busy, will wait forever.
"""
import time
while isGrowing(path, 0.2):  # defined elsewhere by you
time.sleep(1)  # wait a bit
# now we HOPE we can read the file
return open(path, 'r')  # this can fail in many, many ways



do this:


def wait_for_open(pathname):
"""Return file open for reading, or fail. 
If the file is busy, will wait forever.
"""
import time, errno
while True:
try:
return open(path, 'r')
except IOError, e:
if e.errno == errno.EBUSY:
time.sleep(1)
 else:
raise


Note: I've made a guess that the error you get under Windows is 
errno.EBUSY. You'll need to check that for yourself. This whole approach 
assumes that Windows does the sensible thing of returning a unique error 
code when you try to open a file for reading that is already open for 
writing.


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


Re: Need Help Starting Out

2008-03-19 Thread rodmc

> Your best bets are probably Django, Pylons or web.py. But you should
> learn enough of the core language itself before jumping in web stuff IMHO.

Yes, a good point.

If you are looking for general info then then "Dive Into Python" (a
link is on the Python website) is a good start for people who are
familiar with other programming languages. Otherwise I also found
"Python in a Nutshell" useful.

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


Re: Anomaly in time.clock()

2008-03-19 Thread Godzilla
Hi John,

I am using time.clock to calculate the elapsed time. Below is an
example of what I was trying to do:


import time
import thread

class elapseTime:
def __init__(self, name=''):
  self.name = name
  self.timeStamp = None
  self.checkTimeFlag = False
  thread.start_new_thread(self.elapsedTime, ())

def setTime(self, state):
  if state == 1:
self.checkTimeFlag = True
self.timeStamp = time.clock()
  else:
self.checkTimeFlag = False

def elapsedTime(self):
  while True:
curTime = time.clock()
if self.checkTimeFlag:
  if (curTime - self.timeStamp) > 1.0:
print "Elapsed time greater than 1 second. Actual Elapsed
Time", round(curTime-self.timeStamp, 3)
self.checkTimeFlag = False
prevTime = curTime
time.sleep(0.05)

obj = elapseTime()

while True:
  obj.setTime(1)
  time.sleep(10)


But the time.clock() sometimes return a value of between -3.5 to -4.5
seconds backward. Note that not all computers are behaving the same. I
have not experience the same problem with the computer at home.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.path.getsize() on Windows

2008-03-19 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> This whole approach 
> assumes that Windows does the sensible thing of returning a unique 
error 
> code when you try to open a file for reading that is already open for 
> writing.
> 

So how would you use a file to share data then?

By default Python on Windows allows you to open a file for reading 
unless you specify a sharing mode which prevents it: the easiest way is 
probably to call win32file.CreateFile with appropriate parameters.

In one window:
>>> f = open('SHARE.txt', 'w')
>>> f.write('hello')
>>> f.flush()
>>>

and then while that other window is open:

>>> handle = win32file.CreateFile("SHARE.txt",
... win32file.GENERIC_WRITE,
... 0, # i.e. "not shared" is the default
... None,
... win32file.OPEN_ALWAYS,
... win32file.FILE_ATTRIBUTE_NORMAL,
... None)
Traceback (most recent call last):
  File "", line 7, in 
pywintypes.error: (32, 'CreateFile', 'The process cannot access the file 
because it is being used by another process.')
>>> f = open("SHARE.txt", "r")
>>> f.read()
'hello'

The CreateFile call was copied from 
http://mail.python.org/pipermail/python-list/2002-January/122462.html

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


Speaking Text

2008-03-19 Thread David C. Ullrich
Mac OS X has text-to-speech built into the interface.
So there must be a way to access that from the command
line as well - in fact the first thing I tried worked:

os.system('say hello')

says 'hello'.

Is there something similar in Windows and/or Linux?
(If it's there in Linux presumably it only works if there
happens to be a speech engine available...)


David C. Ullrich
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: EuroSciPy 2008 Conference - Leipzig, Germany

2008-03-19 Thread kgmuller
Travis,
A great initiative! I will attend and will submit an abstract of a
presentation on SimPy (Simulation in Python) and how this project will be
brought closer to SciPy.

Any  idea where in Leipzig the conference will be held? I want to book a
hotel in the vicinity of the conference site.

Klaus Müller

> -Original Message-
> From: Travis Vaught [mailto:[EMAIL PROTECTED] 
> Sent: Wednesday, March 12, 2008 4:36 PM
> To: [EMAIL PROTECTED] Org; [EMAIL PROTECTED]; 
> [EMAIL PROTECTED]; Discussion of Numerical Python; 
> [EMAIL PROTECTED]; 
> [EMAIL PROTECTED]; 
> [EMAIL PROTECTED]; 
> [EMAIL PROTECTED]
> Subject: ANN: EuroSciPy 2008 Conference - Leipzig, Germany
> 
> Greetings,
> 
> We're pleased to announce the EuroSciPy 2008 Conference to be 
> held in Leipzig, Germany on July 26-27, 2008.
> 
> http://www.scipy.org/EuroSciPy2008
> 
> We are very excited to create a venue for the European 
> community of users of the Python programming language in 
> science. This conference will bring the presentations and 
> collaboration that we've enjoyed at Caltech each year closer 
> to home for many users of SciPy, NumPy and Python 
> generally--with a similar focus and schedule.
> 
> 
> Call for Participation:
> --
> If you are a scientist using Python for your computational 
> work, we'd love to have you formally present your results, 
> methods or experiences. To apply to present a talk at this 
> year's EuroSciPy, please submit an abstract of your talk as a 
> PDF, MS Word or plain text file to [EMAIL PROTECTED] 
> The deadline for abstract submission is April 30, 2008. 
> Papers and/or presentation slides are acceptable and are due 
> by June 15, 2008. Presentations will be allotted 30 minutes.
> 
> 
> Registration:
> 
> Registration will open April 1, 2008. The registration fee 
> will be 100.00€ for early registrants and will increase to 
> 150.00€ for late registration. Registration will include 
> breakfast, snacks and lunch for Saturday and Sunday.
> 
> 
> Volunteers Welcome:
> --
> If you're interested in volunteering to help organize things, 
> please email us at [EMAIL PROTECTED]
> 
> 
> 
> 
> 
> 
> 
> 
> 

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


Re: Speaking Text

2008-03-19 Thread Bill Scherer
David C. Ullrich wrote:
> Mac OS X has text-to-speech built into the interface.
> So there must be a way to access that from the command
> line as well - in fact the first thing I tried worked:
>
> os.system('say hello')
>
> says 'hello'.
>
> Is there something similar in Windows and/or Linux?
> (If it's there in Linux presumably it only works if there
> happens to be a speech engine available...)
>   
With a little effort, the same code can work on Linux with the Festival
speech engine.

See http://www.cstr.ed.ac.uk/projects/*festival*/


>
> David C. Ullrich
>   

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

Re: Using threads in python is safe ?

2008-03-19 Thread Simon Brunning
On Wed, Mar 19, 2008 at 7:43 AM, Deepak Rokade <[EMAIL PROTECTED]> wrote:
> If jobs to be processed by threds is I/O bound would multithreading help
> python to improve speed of application ?

Probably, yes.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What Programming Languages Should You Learn Next?

2008-03-19 Thread Sean Allen
> Haven't found that killer problem so far ...

for Haskell, check out HAppS. They have
some great web application stuff going on.

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


Re: Pycon disappointment

2008-03-19 Thread Aaron Watters
On Mar 18, 12:55 pm, [EMAIL PROTECTED] wrote:
> Amen on the diamond keynotes and lightning talks. The lightning talks
> were a great disappointment. Sponsor talks (or any such talks pitched
> at selling or recruiting) should go in their own, clearly labeled
> group so those of us who don't care about them can avoid them...

Seconded.  I haven't been at a Python Conf for a long time
but as a former attendee and (not very good) organizer I
have a couple suggestions based on my past experience and
mistakes:

- The conference is too long and it shouldn't be on the weekend.

- Almost all talks should be 10 minutes at most
  with prepared slides and extended abstract with references.

- With much shorter talks you should be able to accept just about any
  properly prepared talk (with abstract and slides) and this
  should reduce the politics and increase the attendance (with
  speakers and some colleagues and maybe broader interest).

I don't know about this conference, but in past conferences
I've been frustrated by people who give out a train of
conscience meander including popping in and out of various console
prompts, editors, web pages, guis... without conveying any useful
information (to me) in 30 minutes.  If you tell them they have
10 minutes and make them get organized in advanced
they are much more likely to get to the point and
everyone can see something else before they run out of
attention span.

   -- Aaron Watters

===
bye bye petroleum!  good riddance.
http://biofuels.usu.edu/htm/initiative

http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=pretty+boring
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lock access to serial port

2008-03-19 Thread Grant Edwards
On 2008-03-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> how to get ttyS0 serial port for exclusive access? I have a python
> script that uses this device with AT commands. I need that two
> instances can call simultaneosuly this python script but only one of
> them gets the device. I tried fcntl.flock, it was just ignored, put
> writtable file LCK..ttyS0 in /var/lock,

Using a lock file is the traditional method of providing
mutually exclusive access to a serial port.

> tried ioctl (but I may not know what are appropriate
> arguments), googled half a day for various phrases, error
> messages etcwithout success.

It's unclear what "without success" means.  Lockfiles have been
used for decades, and they work fine as long as all of the
applications follow the rules.

-- 
Grant

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


Re: lock access to serial port

2008-03-19 Thread [EMAIL PROTECTED]
hmm, now it seems I get to the locking
try:
ser = serial.Serial(dev, 19200, rtscts=1, timeout=1)
if ser.isOpen():
try:
fcntl.lockf(ser,fcntl.LOCK_EX)
but get into some weirdness - trying to lock does not time out! The
script stops at this line and waits ?for ever? (it waits for 15
minutes at least, that I have tried).

Andra


> not the goal setup but the way I tried it out - a webpage to send an
> sms to mobile phone. This is an php what calls a python script. A
> python script opens serial device, checks for gsm network, sends a
> message - on all the way I try to make sure that appropriate answers
> are received from the gsm device so that I know that all is going well
> (and if not - cancel it with error message).
>
> Testing it with sending an sms from two open webpages, I normally got
> that one message was sent and for the other I received "try once more,
> happened that and that". But I got also an inadmissible situation -
> the received sms contained also unwanted text. As far as I can realize
> how to deal with it is not allowing writing to the device for two
> processes simultaneously.
>
> Andra
>
> On 19 Marts, 11:00, taco <[EMAIL PROTECTED]> wrote:
>
> > [EMAIL PROTECTED] wrote:
> > > hello group,
>
> > > how to get ttyS0 serial port for exclusive access? I have a python
> > > script that uses this device with AT commands. I need that two
> > > instances can call simultaneosuly this python script but only one of
> > > them gets the device. I tried fcntl.flock, it was just ignored, put
> > > writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not
> > > know what are appropriate arguments), googled half a day for various
> > > phrases, error messages etcwithout success.
>
> > > please help,
>
> > > Andra
>
> > not sure if I understand you well, but how about a server application which
> > accepts 2 clients which can send messages which are output on the serial
> > device? The serial device access protected with a mutex while receiving
> > messages done in 2 threads or something.
> > taco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speaking Text

2008-03-19 Thread Hans Georg Krauthäuser
On 19 Mrz., 13:41, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> Mac OS X has text-to-speech built into the interface.
> So there must be a way to access that from the command
> line as well - in fact the first thing I tried worked:
>
> os.system('say hello')
>
> says 'hello'.
>
> Is there something similar in Windows and/or Linux?
> (If it's there in Linux presumably it only works if there
> happens to be a speech engine available...)
>
> David C. Ullrich

In Windows -> pyTTS

http://www.mindtrove.info/articles/pytts.html

Regards
Hans Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speaking Text

2008-03-19 Thread Duncan Booth
David C. Ullrich <[EMAIL PROTECTED]> wrote:

> os.system('say hello')
> 
> says 'hello'.
> 
> Is there something similar in Windows and/or Linux?
> (If it's there in Linux presumably it only works if there
> happens to be a speech engine available...)

Perhaps http://www.mindtrove.info/articles/pytts.html ?

Or if all else fails Python can drive Microsoft's MSAGENT for speaking 
animated figures.
-- 
http://mail.python.org/mailman/listinfo/python-list


[Q] SOAP Server in Python

2008-03-19 Thread Eric
What is the best, well supported, way to write a SOAP Server in
Python? Where can a good example be found?
I do have a WSDL file.

In PHP5, it is rather trivial to write a SOAP server once one has a
WSDL file. For example, a simple SOAP Server written using PHP5 might
look like:

setClass( "MySoapServer" );
$server->handle();
?>

I am basically looking to do the same thing in Python as easily.

Any help or pointers would be appreciated.

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


changing names of items in a list

2008-03-19 Thread royG
hi
i am trying to rename extension of files in a directory..as an initial
step i made a method in

class ConvertFiles:
 def __init__(self,infldr,outfldr):
 self.infldr=infldr
 self.outfldr=outfldr
 self.origlist=os.listdir(infldr)

 def renamefiles(self,extn):
 for x in self.origlist:
 x=x+"."+extn

...

later when i print self.origlist  i find that the elements of list are
unchanged..even tho  a print x  inside the renamefiles()  shows that
extn is appended to x  ..
why does this happen?
RG



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


Re: lock access to serial port

2008-03-19 Thread Andra
I tried ready-made commands for file locking, and turned to that LCK
file just in case some permissions are wrong and that's the reason the
commands fail.

On 19 Marts, 15:43, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-03-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > how to get ttyS0 serial port for exclusive access? I have a python
> > script that uses this device with AT commands. I need that two
> > instances can call simultaneosuly this python script but only one of
> > them gets the device. I tried fcntl.flock, it was just ignored, put
> > writtable file LCK..ttyS0 in /var/lock,
>
> Using a lock file is the traditional method of providing
> mutually exclusive access to a serial port.
>
> > tried ioctl (but I may not know what are appropriate
> > arguments), googled half a day for various phrases, error
> > messages etcwithout success.
>
> It's unclear what "without success" means.  Lockfiles have been
> used for decades, and they work fine as long as all of the
> applications follow the rules.
>
> --
> Grant
-- 
http://mail.python.org/mailman/listinfo/python-list


Generalizing PEP 370 (per user site-packages directory) via .pth files

2008-03-19 Thread ago
Dear all,

I was reading pep 370, "Per user site-packages directory"
http://www.python.org/dev/peps/pep-0370/, and was wondering if the
concept couldn't be generalized by having ways to pass a .pth file as
commandline argument and/or via an environment variable (PYTHONPATH
could also be used to feed .pth files) and/or via special named files
such as ~/.python2.6-user.pth or ./python2.6-local.pth, or possibly
even reusing the paths in the distutils configuration files (under
[install]).

Any path in the above files would be added to sys.path and scanned
recursively for other pth files.  The system would also load
default.pth from a pre-defined location (e.g. /etc/python2.6/
default.pth), which would point to the default site-packages
directory. There should also be a mechanism to disable/override
default.pth for situations where a clean environment is desired.

This would make it easier to setup special testing environments,
perform local installations, and allow for file-based deployments (in
simple scenarios), without resorting to special tools such as virtual-
python, editing site.py and/or requiring sysadmin intervention. It
would be particularly useful in environments where there is a clear
separation between IT and developer roles.

I just started giving some thoughts to the concept and I am not fully
aware of the implications and requirements of the proposal, but even
if the above turns out to be impractical, I hope that a debate on the
topic will be beneficial.

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


Re: changing names of items in a list

2008-03-19 Thread Diez B. Roggisch
royG wrote:

> hi
> i am trying to rename extension of files in a directory..as an initial
> step i made a method in
> 
> class ConvertFiles:
>  def __init__(self,infldr,outfldr):
>  self.infldr=infldr
>  self.outfldr=outfldr
>  self.origlist=os.listdir(infldr)
> 
>  def renamefiles(self,extn):
>  for x in self.origlist:
>  x=x+"."+extn
> 
> ...
> 
> later when i print self.origlist  i find that the elements of list are
> unchanged..even tho  a print x  inside the renamefiles()  shows that
> extn is appended to x  ..
> why does this happen?

Because a piece of code like this

x = some_list[index]
x = something_else()

doesn't change the object itself, just rebinds x to a new object. That the
old object stored in x happened to be referenced in a list as well - who
cares?

So either your members of origlist become mutables - then you have to alter
them, and then they will be reachable from the list. Like this:

class Foo(object):
def __init__(self):
pass

l = [Foo() for _ in xrang(10)]

f = l[0]
f.bar = "baz"

print l[0].bar

Or you rebind the list itself, or it's index under work - like this:

for i, item in enumerate(l):
l[i] = do_something_with_item(item)

or

new_l = []
for item in l:
new_l.append(do_something(item))
l = new_l

There are innumerable variations of this scheme. 

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


Re: changing names of items in a list

2008-03-19 Thread Simon Brunning
On Wed, Mar 19, 2008 at 2:21 PM, royG <[EMAIL PROTECTED]> wrote:
> hi
>  i am trying to rename extension of files in a directory..as an initial
>  step i made a method in
>
>  class ConvertFiles:
>  def __init__(self,infldr,outfldr):
>  self.infldr=infldr
>  self.outfldr=outfldr
>  self.origlist=os.listdir(infldr)
>  
>  def renamefiles(self,extn):
>  for x in self.origlist:
>  x=x+"."+extn
>
>  ...
>
>  later when i print self.origlist  i find that the elements of list are
>  unchanged..even tho  a print x  inside the renamefiles()  shows that
>  extn is appended to x  ..
>  why does this happen?

Your 'x=' line is building a brand new string, and rebinding the name
'x' to it. It's not doing anything to the original list. See
.

I'd rewrite that as (untested):

def renamefiles(self, extn):
self.origlist = list((x + "." + extn) for x in self.origlist)

or

def renamefiles(self, extn):
self.origlist = list(("%s.%s" % (z, extn)) for x in self.origlist)

Better still, take a look at the os.path module...

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


Improving datetime

2008-03-19 Thread Nicholas F. Fabry
This is a query for information as to how to proceed.  I am not a  
professional programmer, but I use Python a great deal to help me in  
my main job, which involves designing schedules for a global airline.   
As such, I use datetime (and dateutil) extensively, and after much  
use, I have come to some conclusions about their utility, and how to  
improve them.  Some of these changes are quite minor and would result  
in a large increase in utility (low hanging fruit), while some changes  
are major, and would result in less obvious benefits - but these  
changes would increase the 'Python Zen' of them.

So - where should I propose these changes?  Here?  python-dev?  Should  
I write up a full PEP or should I just give a more informal outline  
with code samples?  I would volunteer to help maintain/improve  
datetime, but I don't speak C at all, unfortunately, and datetime  
appears to be in C.

In addition, I have little contact with the Python community - I work  
somewhat 'solo' when it comes to my programming projects.  So, are  
there other people out there who use datetime?  Dateutil?  What do you  
find the deficits/benefits of these modules to be?

Thank you for your thoughts

Nick Fabry

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


Re: Improving datetime

2008-03-19 Thread Mike Driscoll
On Mar 19, 9:12 am, "Nicholas F. Fabry" <[EMAIL PROTECTED]>
wrote:
> This is a query for information as to how to proceed.  I am not a
> professional programmer, but I use Python a great deal to help me in
> my main job, which involves designing schedules for a global airline.
> As such, I use datetime (and dateutil) extensively, and after much
> use, I have come to some conclusions about their utility, and how to
> improve them.  Some of these changes are quite minor and would result
> in a large increase in utility (low hanging fruit), while some changes
> are major, and would result in less obvious benefits - but these
> changes would increase the 'Python Zen' of them.
>
> So - where should I propose these changes?  Here?  python-dev?  Should
> I write up a full PEP or should I just give a more informal outline
> with code samples?  I would volunteer to help maintain/improve
> datetime, but I don't speak C at all, unfortunately, and datetime
> appears to be in C.
>
> In addition, I have little contact with the Python community - I work
> somewhat 'solo' when it comes to my programming projects.  So, are
> there other people out there who use datetime?  Dateutil?  What do you
> find the deficits/benefits of these modules to be?
>
> Thank you for your thoughts
>
> Nick Fabry

I think you need to do this sort of thing on python-dev. I'm not sure
how the PEP process works though. If you give your thoughts in a PEP-
like format, you'd probably be taken more seriously though.

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


Re: SOAP Server in Python

2008-03-19 Thread dave_mikesell
On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:

> I am basically looking to do the same thing in Python as easily.
>
> Any help or pointers would be appreciated.

Googling for "python soap" turned up a few hits that may help you.


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


cx_Oracle execute procedure

2008-03-19 Thread Poppy
I've been working on the code below and and executes silently, no 
complaints, however the end result should be a record in my table and it's 
not added. The procedure works with the passed credentials using SQLPlus or 
SQL Developer clients. However I'm not sure if I'm constructing my python 
code correctly to interact with Oracle.

I've been basing the code below on what I found in this thread 
http://www.thescripts.com/forum/thread33728.html .

Zach-

import cx_Oracle

connection = cx_Oracle.connect("user/[EMAIL PROTECTED]")

## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum 
varchar2, p_prefix number)

cur = connection.cursor()

repParams = {}
repParams['arg1'] = "555"
repParams['arg2'] = "2"
repParams['arg3'] = "999"

sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3); 
end;"""

cur.execute(sqlStr, repParams)

connection.commit

cur.close

connection.close


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


How to get an XML DOM while offline?

2008-03-19 Thread william tanksley
I want to parse my iTunes Library xml. All was well, until I unplugged
and left for the train (where I get most of my personal projects
done). All of a sudden, I discovered that apparently the presence of a
DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing
the Internet... So suddenly I was unable to do any work.

I don't want to modify the iTunes XML; iTunes rewrites it too often.
How can I prevent xml.dom.minidom from dying when it can't access the
Internet?

Is there a simpler way to read the iTunes XML? (It's merely a plist,
so the format is much simpler than general XML.)

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


Re: cx_Oracle execute procedure

2008-03-19 Thread Jerry Hill
On Wed, Mar 19, 2008 at 11:03 AM, Poppy <[EMAIL PROTECTED]> wrote:
> I've been working on the code below and and executes silently, no
>  complaints, however the end result should be a record in my table and it's
>  not added. The procedure works with the passed credentials using SQLPlus or
>  SQL Developer clients. However I'm not sure if I'm constructing my python
>  code correctly to interact with Oracle.
...
>  connection.commit
>  cur.close
>  connection.close

You have to actually call these methods:
connection.commit()
cur.close()
connection.close()

Without the parentheses, you're just getting a reference to the
methods and immediately discarding them.

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


Re: Speaking Text

2008-03-19 Thread Grant Edwards
On 2008-03-19, David C  Ullrich <[EMAIL PROTECTED]> wrote:
> Mac OS X has text-to-speech built into the interface.
> So there must be a way to access that from the command
> line as well - in fact the first thing I tried worked:
>
> os.system('say hello')
>
> says 'hello'.
>
> Is there something similar in Windows and/or Linux?

The only speach sythesizer I've seen on Linux boxes is festival:

  http://www.cstr.ed.ac.uk/projects/festival/

You can use os.system() to run it from the "command line" or
there are various client APIs:

  http://www.cstr.ed.ac.uk/projects/festival/manual/festival_28.html#SEC126

But, it's not installed by default on any distros I've ever
used...

-- 
Grant

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


Re: Improving datetime

2008-03-19 Thread Preston Landers
On Mar 19, 9:12 am, "Nicholas F. Fabry" <[EMAIL PROTECTED]>
wrote:

> So - where should I propose these changes?  Here?  python-dev?  Should  
> I write up a full PEP or should I just give a more informal outline  
> with code samples?  

My guess is that the python-dev folks would send you here or to the
python-ideas mailing list.  My suggestion is to give a more informal
outline with code samples either here or in python-ideas before
proceeding any further.

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


Re: How to get an XML DOM while offline?

2008-03-19 Thread Diez B. Roggisch
william tanksley wrote:

> I want to parse my iTunes Library xml. All was well, until I unplugged
> and left for the train (where I get most of my personal projects
> done). All of a sudden, I discovered that apparently the presence of a
> DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing
> the Internet... So suddenly I was unable to do any work.
> 
> I don't want to modify the iTunes XML; iTunes rewrites it too often.
> How can I prevent xml.dom.minidom from dying when it can't access the
> Internet?
> 
> Is there a simpler way to read the iTunes XML? (It's merely a plist,
> so the format is much simpler than general XML.)

Normally, this should be solved using an entity-handler that prevents the
remote fetching. I presume the underlying implementation of a SAX-parser
does use one, but you can't override that (at least I didn't find anything
in the docs)

The most pragmatic solution would be to rip the doctype out using simple
string methods and/or regexes.

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


Re: cx_Oracle execute procedure

2008-03-19 Thread Diez B. Roggisch
Poppy wrote:

> I've been working on the code below and and executes silently, no
> complaints, however the end result should be a record in my table and it's
> not added. The procedure works with the passed credentials using SQLPlus
> or SQL Developer clients. However I'm not sure if I'm constructing my
> python code correctly to interact with Oracle.
> 
> I've been basing the code below on what I found in this thread
> http://www.thescripts.com/forum/thread33728.html .
> 
> Zach-
> 
> import cx_Oracle
> 
> connection = cx_Oracle.connect("user/[EMAIL PROTECTED]")
> 
> ## PROCEDURE rptmgr.rep_utils.CLONE_REPORT( p_ordernum varchar2,p_repnum
> varchar2, p_prefix number)
> 
> cur = connection.cursor()
> 
> repParams = {}
> repParams['arg1'] = "555"
> repParams['arg2'] = "2"
> repParams['arg3'] = "999"
> 
> sqlStr = """BEGIN rptmgr.rep_utils.CLONE_REPORT( :arg1, :arg2, :arg3);
> end;"""
> 
> cur.execute(sqlStr, repParams)
> 
> connection.commit
> 
> cur.close
> 
> connection.close

You forgot to call the methods using the ()-operator.

connection.commit()

and so forth.

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


Re: SOAP Server in Python

2008-03-19 Thread Eric
On Mar 19, 10:59 am, [EMAIL PROTECTED] wrote:
> On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:
>
> > I am basically looking to do the same thing in Python as easily.
>
> > Any help or pointers would be appreciated.
>
> Googling for "python soap" turned up a few hits that may help you.

Yes, but I don't have the knowledge to accurately or effectively
evaluate the information. I was hoping someone here had some
experience writing a SOAP Server using Python and would be willing to
share what they know.


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


Re: SOAP Server in Python

2008-03-19 Thread Eric
On Mar 19, 10:59 am, [EMAIL PROTECTED] wrote:
> On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:
>
> > I am basically looking to do the same thing in Python as easily.
>
> > Any help or pointers would be appreciated.
>
> Googling for "python soap" turned up a few hits that may help you.

Yes, but I don't have the knowledge to accurately or effectively
evaluate the information. I was hoping someone here had some
experience writing a SOAP Server using Python and would be willing to
share what they know.


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


Re: cx_Oracle execute procedure

2008-03-19 Thread Poppy
Thanks Jerry and Diez. The first two replies I found answered my noob 
question.


"Jerry Hill" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Wed, Mar 19, 2008 at 11:03 AM, Poppy <[EMAIL PROTECTED]> 
> wrote:
>> I've been working on the code below and and executes silently, no
>>  complaints, however the end result should be a record in my table and 
>> it's
>>  not added. The procedure works with the passed credentials using SQLPlus 
>> or
>>  SQL Developer clients. However I'm not sure if I'm constructing my 
>> python
>>  code correctly to interact with Oracle.
> ...
>>  connection.commit
>>  cur.close
>>  connection.close
>
> You have to actually call these methods:
> connection.commit()
> cur.close()
> connection.close()
>
> Without the parentheses, you're just getting a reference to the
> methods and immediately discarding them.
>
> -- 
> Jerry 


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


csv.Sniffer - delete in Python 3.0?

2008-03-19 Thread skip

The csv module contains a Sniffer class which is supposed to deduce the
delimiter and quote character as well as the presence or absence of a header
in a sample taken from the start of a purported CSV file.  I no longer
remember who wrote it, and I've never been a big fan of it.  It determines
the delimiter based almost solely on character frequencies.  It doesn't
consider what the actual structure of a CSV file is or that delimiters and
quote characters are almost always taken from the set of punctuation or
whitespace characters.  Consequently, it can cause some occasional
head-scratching:

>>> sample = """\
... abc8def
... def8ghi
... ghi8jkl
... """
>>> import csv
>>> d = csv.Sniffer().sniff(sample)
>>> d.delimiter
'8'
>>> sample = """\
... a8bcdef
... ab8cdef
... abc8def
... abcd8ef
... """
>>> d = csv.Sniffer().sniff(sample)
>>> d.delimiter
'f'

It's not clear to me that people use letters or digits very often as
delimiters.  Both samples above probably represent data from single-column
files, not double-column files with '8' or 'f' as the delimiter.

I would be happy to get rid of it in 3.0, but I'm also aware that some
people use it.  I'd like feedback from the Python community about this.  If
I removed it is there someone out there who wants it badly enough to
maintain it in PyPI?

Thanks,

-- 
Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/
-- 
http://mail.python.org/mailman/listinfo/python-list


url validator in python

2008-03-19 Thread vvangelovski
How can I check the validity of absolute urls with http scheme?
example:
"http://www.example.com/something.html"; -> valid
"http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid
-- 
http://mail.python.org/mailman/listinfo/python-list


how to remove suffix from filename

2008-03-19 Thread royG

hi
when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/
two.jpg'] etc i want to extract the
basename without the suffix...ie i want to get 'one','two' etc and not
'one.jpg'

is there a function in python to do this or do i have tosplit it ..?
thanks
RG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is hash map data structure available in Python?

2008-03-19 Thread sturlamolden
On 19 Mar, 09:40, grbgooglefan <[EMAIL PROTECTED]> wrote:

> How do I create hash map in Python?

Python dictionaries are the fastest hash maps known to man.

If you need persistent storage of your hash map, consider module bsddb
or dbhash.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove suffix from filename

2008-03-19 Thread Mel
royG wrote:
> when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/
> two.jpg'] etc i want to extract the
> basename without the suffix...ie i want to get 'one','two' etc and not
> 'one.jpg'
> 
> is there a function in python to do this or do i have tosplit it ..?
> thanks

os.path.splitext is the one, it think.

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


add new csv line

2008-03-19 Thread Alexandru Dumitrescu
Hello everybody,
Is there a way to add a new line at the beginning of  a  *.csv file,
line which contain the name of the columns?
-- 
http://mail.python.org/mailman/listinfo/python-list

ADO error - large data set

2008-03-19 Thread Gyula
Hi there,

I have been running Python to tap into an MS Access 2003 database
using ADO (PythonWin+COM). Everything works great creating recordsets
etc. when I open a table with a small number of records. However, when
I try to run the same Python code with a large table (>100,000) I get:

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework
\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\Documents and Settings\user\Desktop\PythonWS\scripts
\readmsaccess.py", line 43, in 
rs.Open('SELECT * FROM ' + tblname, oConn, 1, 3)
  File "C:\Python25\lib\site-packages\win32com\gen_py\2A75196C-
D9EB-4129-B803-931327F72D5Cx0x2x8.py", line 2364, in Open
, ActiveConnection, CursorType, LockType, Options)
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None,
5003251, -2147467259), None)

The small and large table structures are identical, all I do is change
the tblname from input1000 (1000 records) to input (>10 records).
I use optimistic locking and keyset cursor..nothing out of the
ordinary?

Any ideas? ADO 2.8 is what I am using.

Thanks a lot!
GG
-- 
http://mail.python.org/mailman/listinfo/python-list


Python to C/C++

2008-03-19 Thread Blubaugh, David A.
To All,


Has anyone worked with a translator that will translate python to c/c++
source code?  I know that there is already one translator of this nature
(shedskin compiler) out there.  However, it is still in the beta stage
of development.  Does anyone know of a more developed version of a
translator of this nature?   

Thanks,

David Blubaugh

This e-mail transmission contains information that is confidential and may be 
privileged.   It is intended only for the addressee(s) named above. If you 
receive this e-mail in error, please do not read, copy or disseminate it in any 
manner. If you are not the intended recipient, any disclosure, copying, 
distribution or use of the contents of this information is prohibited. Please 
reply to the message immediately by informing the sender that the message was 
misdirected. After replying, please erase it from your computer system. Your 
assistance in correcting this error is appreciated.


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

Re: url validator in python

2008-03-19 Thread Tim Chase
> How can I check the validity of absolute urls with http scheme?
> example:
> "http://www.example.com/something.html"; -> valid
> "http://www.google.com/ + Brite_AB_Iframe_URL + " -> invalid

You could try something like

   import urllib
   tests = (
 ("http://www.google.com/ + Brite_AB_Iframe_URL + ", False),
 ("http://www.example.com/something.html";, True),
 ("https://www.google.com/ + Brite_AB_Iframe_URL + ", False),
 ("https://www.example.com/something.html";, True),
   )
   def no_method(url):
 if ':' in url[:7]:
   # strip off the leading http:
   return url.split(':', 1)[1]
 return url

   def is_valid_url(url):
 url = no_method(url)
 return url == urllib.quote(url)

   for test_url, expected_result in tests:
 print "Testing %s\nagainst %s" % (
   no_method(test_url),
   urllib.quote(no_method(test_url))
   )
 actual_result = is_valid_url(test_url)
 print 'Pass: %s' % (actual_result == expected_result)
 print '='*70

The reason for the no_method() is that otherwise it gets 
normalized to "http%3A//..." so you have to strip off that bit 
before comparing.

-tkc




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


Re: Python to C/C++

2008-03-19 Thread Michael Wieher
I think py2exe does this, but it might be a bit bloated

2008/3/19, Blubaugh, David A. <[EMAIL PROTECTED]>:
>
>  To All,
>
> Has anyone worked with a translator that will translate python to c/c++
> source code?  I know that there is already one translator of this nature 
> (shedskin
> compiler) out there.  However, it is still in the beta stage of
> development.  Does anyone know of a more developed version of a translator
> of this nature?
>
> Thanks,
>
> David Blubaugh
>
> This e-mail transmission contains information that is confidential and may
> be privileged.   It is intended only for the addressee(s) named above. If
> you receive this e-mail in error, please do not read, copy or disseminate it
> in any manner. If you are not the intended recipient, any disclosure,
> copying, distribution or use of the contents of this information is
> prohibited. Please reply to the message immediately by informing the sender
> that the message was misdirected. After replying, please erase it from your
> computer system. Your assistance in correcting this error is appreciated.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: csv.Sniffer - delete in Python 3.0?

2008-03-19 Thread Robin Becker
[EMAIL PROTECTED] wrote:

> 
> I would be happy to get rid of it in 3.0, but I'm also aware that some
> people use it.  I'd like feedback from the Python community about this.  If
> I removed it is there someone out there who wants it badly enough to
> maintain it in PyPI?
..
sounds like we really need

import ai

info = ai.guess_what_this_is('crummy.csv')

but I suspect that won't arrive before py5000

I use csv, but almost always with tab or comma separation and \r\n line 
terminators.
-- 
Robin Becker

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


Prototype OO

2008-03-19 Thread sam

Some time ago (2004) there were talks about prototype-based languages and 
Prothon emerged.

Can someone tell me why class-based OO is better that Prototype based, 
especially in scripting langage with dynamic types as Python is?


Here are some links:

http://c2.com/cgi/wiki?PrototypeBasedProgramming
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Class-Based_vs._Prototype-Based_Languages



--
UFO Occupation
www.totalizm.pl
-- 
http://mail.python.org/mailman/listinfo/python-list


Latest updates inSQL server and other programming laguages like C++/Java

2008-03-19 Thread Gokul
The latest developments in SQL server 2008 and an complete
encyclopedia of microsoft softwares. Know the methodology to capture
customers requirements for new products. Get the latest development in
C++ and other IT related tools. A complete tutor for all your IT
needs. Visit

http://www.sqlserversoftware.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Help Starting Out

2008-03-19 Thread Peter Decker
On Tue, Mar 18, 2008 at 11:10 AM, jmDesktop <[EMAIL PROTECTED]> wrote:
> Hi, I would like to start using Python, but am unsure where to begin.
>  I know how to look up a tutorial and learn the language, but not what
>  all technologies to use.  I saw references to plain Python, Django,
>  and other things.
>
>  I want to use it for web building with database access.  What do I use
>  for that?  Does it matter what I use on the client side (mootools, or
>  whatever)?

If you are going to be developing web applications, there are many
excellent frameworks available, all of which provide database support.
If you are looking to develop desktop applications, you should check
out Dabo (http://dabodev.com). They integrate data access and GUI
controls, making it simple to create database apps. They use wxPython
for the UI layer, but hide all of its ugliness, allowing you to
program to a clean, consistent API for your GUI.


-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using threads in python is safe ?

2008-03-19 Thread Gabriel Genellina
En Wed, 19 Mar 2008 04:43:34 -0300, Deepak Rokade <[EMAIL PROTECTED]>  
escribió:

> Thanks all for removing confusion about GIL,
> one more question;
> If jobs to be processed by threds is I/O bound would multithreading help
> python to improve speed of application ?
> Since I read that " multithreading is not a good strategy to improve  
> speed
> of python application."

Try and see what happens in your specific case. People keeps saying that  
but I've never seen conclusive evidence on this topic. Using several  
threads for I/O bound tasks seems reasonable to me, and is the easiest  
approach. For CPU bound tasks, multiple threads won't help much, be it  
Python or another language.
I mean, a reasonable number of threads with a reasonable task load. A  
server handling thousands of simultaneous connections is another beast.

-- 
Gabriel Genellina

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


Re: How to get an XML DOM while offline?

2008-03-19 Thread Paul Boddie
On 19 Mar, 16:27, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> william tanksley wrote:
> > I want to parse my iTunes Library xml. All was well, until I unplugged
> > and left for the train (where I get most of my personal projects
> > done). All of a sudden, I discovered that apparently the presence of a
> > DOCTYPE in the iTunes XML makes xml.dom.minidom insist on accessing
> > the Internet... So suddenly I was unable to do any work.

The desire to connect to the Internet for DTDs is documented in the
following bug:

http://bugs.python.org/issue2124

However, I can't reproduce the problem using xml.dom.minidom.parse/
parseString and plain XHTML, although I may be missing something which
activates the retrieval of the DTD.

> > I don't want to modify the iTunes XML; iTunes rewrites it too often.
> > How can I prevent xml.dom.minidom from dying when it can't access the
> > Internet?
>
> > Is there a simpler way to read the iTunes XML? (It's merely a plist,
> > so the format is much simpler than general XML.)
>
> Normally, this should be solved using an entity-handler that prevents the
> remote fetching. I presume the underlying implementation of a SAX-parser
> does use one, but you can't override that (at least I didn't find anything
> in the docs)

There's a lot of complicated stuff in the xml.dom package, but I found
that the DOMBuilder class (in xml.dom.xmlbuilder) probably contains
the things which switch such behaviour on or off. That said, I've
hardly ever used the most formal DOM classes to parse XML in Python
(where you get the DOM implementation and then create other factory
classes - it's all very "Java" in nature), so the precise incantation
is unknown/forgotten to me.

> The most pragmatic solution would be to rip the doctype out using simple
> string methods and/or regexes.

Maybe, but an example fragment of the XML might help us diagnose the
problem, ideally with some commentary from the people who wrote the
xml.dom software in the first place.

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


Python to C/C++

2008-03-19 Thread Patrick Mullen
(sorry michael, didn't mean to personal post

On Wed, Mar 19, 2008 at 9:24 AM, Michael Wieher wrote:
 > I think py2exe does this, but it might be a bit bloated

 No, py2exe basically bundles the main script and the interpreter
 together so it's easy to run and requires no python installation.

 Look into pyrex and pypy.  A mature translator doesn't exist.  Also
 there is ctypes which goes in reverse letting you use more c from
 python easily.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anomaly in time.clock()

2008-03-19 Thread Ross Ridge
Godzilla  <[EMAIL PROTECTED]> wrote:
>But the time.clock() sometimes return a value of between -3.5 to -4.5
>seconds backward.

There are race conditions in your code.  In between the time you execute
"curTime = time.clock()" and calculate "curTime - self.timeStamp" in one
thread, the other thread can execute "self.timeStamp = time.clock()".
It's the only way your example program can print a negative "Actual
Elapsed Time" value.  The race condition seems unlikely, and it's hard
to explain how this could result in it printing a value in the range
of -3.5 to -4.5.  However, a race condition occuring between the two
evaluations of "curTime - self.timeStamp" is the only way your example
program could print a negative value.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter.Text widget - how to get text cursor position?

2008-03-19 Thread Alex9968
Is it possible to get position (in numbers) of the insertion cursor? As 
I understood, Text widget uses mark named INSERT to store it, which is 
available globally by just referencing INSERT, but how could I get 
actual coordinate numbers of the mark?
I need this because I want not just to insert string at, but to examine 
text before and after the insertion cursor. I can probably use .get() to 
extract the halves of text before and after cursor, but it'd be better 
just to know the position.

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


Re: xml sax

2008-03-19 Thread Robert Bossy
Timothy Wu wrote:
> Hi,
>
> I am using  xml.sax.handler.ContentHandler to parse some simple xml.
>
> I want to detect be able to parse the content of this tag embedded in 
> the XML.
> 174
>
>
> Is the proper way of doing so involving finding the "Id" tag 
> from startElement(), setting flag when seeing one, and in characters(),
> when seeing that flag set, save the content?
>
> What if multiple tags of the same name are nested at different levels
>
> and I want to differentiate them? I would be setting a flag for each level.
> I can imagine things get pretty messy when flags are all around.
>   
Hi,

You could have a list of all opened elements from the root to the 
innermost. To keep such a list, you append the name of the element to 
this stack at the end of startElement() and pop it off at the end of 
endElement().

In this way you have acces to the path of the current parser position. 
In order to differentiate between character data in Id and in Id/Id, you 
just have to iterate at the last elements of the list.

Cheers,
RB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to remove suffix from filename

2008-03-19 Thread Larry Bates
royG wrote:
> hi
> when parsing a list of filenames like ['F:/mydir/one.jpg','F:/mydir/
> two.jpg'] etc i want to extract the
> basename without the suffix...ie i want to get 'one','two' etc and not
> 'one.jpg'
> 
> is there a function in python to do this or do i have tosplit it ..?
> thanks
> RG

import os

fname='F:/mydir/two.jpg'
filenameonly=os.path.splitext(os.path.basename(fname))[0]

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


  1   2   >