Potential Python 3.3.2 pyvenv bug on Windows

2013-06-15 Thread peter
I've recently hit an issue with pyvenv that is causing AttributeErrors in other 
packages on Windows (see 
https://groups.google.com/forum/?fromgroups#!topic/pylons-discuss/FpOSMDpdvy4). 
 Here's what I believe is going on:

On Windows, the pyvenv pydoc script has a .py extension - so import finds it 
instead of the system's pydoc module.  On Linux, the pyvenv pydoc script 
doesn't have an extension - so import finds the system's pydoc module.

I believe the Windows pyvenv pydoc.py script should be renamed to pydocs.py.

Has anyone else hit this issue?

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


Re: Potential Python 3.3.2 pyvenv bug on Windows

2013-06-15 Thread peter
Agreed.  I did submit a bug report.  If the core developers fix this, I suspect 
they will do so in a manner that does not break existing docs.  However, my 
workaround (rename the pyvenv created scripts\pydoc.py file) should suffice for 
those who need the problem solved now.

Take care,

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


help with explaining how to split a list of tuples into parts

2013-07-12 Thread peter
Hi List,

I am new to Python and wondering if there is a better python way to do 
something.  As a learning exercise I decided to create a python bash script to 
wrap around the Python Crypt library (Version 2.7).

My attempt is located here - https://gist.github.com/pjfoley/5989653

I am trying to wrap my head around list comprehensions, I have read the docs at 
http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions and 
read various google results.  I think my lack of knowledge is making it 
difficult to know what key word to search on.

Essentially I have this list of tuples

# Tuple == (Hash Method, Salt Length, Magic String, Hashed Password Length)
supported_hashes=[('crypt',2,'',13), ('md5',8,'$1$',22), 
('sha256',16,'$5$',43), ('sha512',16,'$6$',86)]

This list contains the valid hash methods that the Crypt Library supports plus 
some lookup values I want to use in the code.

I have managed to work out how to extract a list of just the first value of 
each tuple (line 16) which I use as part of the validation against the --hash 
argparse option.

My Question.

Looking at line 27, This line returns the tuple that mataches the hash type the 
user selects from the command line.  Which I then split the seperate parts over 
lines 29 to 31.

I am wondering if there is a more efficient way to do this such that I could do:

salt_length, hash_type, expected_password_length = [x for x in supported_hashes 
if x[0] == args.hash]

>From my limited understanding the first x is the return value from the 
>function which meets the criteria.  So could I do something like:

... = [(x[0][1], x[0][2], x[0][3]) for x in supported_hashes if x[0] == 
args.hash]

I am happy to be pointed to some documentation which might help clarify what I 
need to do.  

Also if there is anything else that could be improved on with the code happy to 
be contacted off list.

Thanks,

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


Re: help with explaining how to split a list of tuples into parts

2013-07-13 Thread peter
On Saturday, 13 July 2013 17:28:50 UTC+10, Peter Otten  wrote:
> 
> Every time when you have to look up something you should think 'dict', and I
> 
> expect that pretty that will happen automatically.
> 
> Also, to split a tuple into its items you can "unpack" it:
> 
> 
> 
> triple = (1, 2, 3)
> 
> one, two, three = triple
> 
> assert one == 1 and two == 2 and three == 3
> 
> 
> 
> So:
> 
> 
> 
> supported_hashes = {
> 
> "crypt": (2, "", 13),
> 
> "md5": (8, "$1$", 22),
> 
> ...
> 
> }
> 
> ...
> 
> parser.add_argument(
> 
> '--hash', default='sha512', 
> 
> choices=supported_hashes, # accept the keys
> 
> help='Which Hash function to use')
> 
> ...
> 
> salt_length, hash_type, expected_password_length = supported_hashes[args.hash]
> 
> ...

Hi Peter,

Thanks for the pointers I will try your suggestion out and read some more.

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


Re: help with explaining how to split a list of tuples into parts

2013-07-13 Thread peter
On Saturday, 13 July 2013 18:11:18 UTC+10, Steven D'Aprano  wrote:
> On Fri, 12 Jul 2013 23:43:55 -0700, peter wrote:
> > 
> > I am new to Python and wondering if there is a better python way to do
> 
> A Python bash script? What does that mean? Python and bash are two 
> different languages.

Sorry I was trying to give some context, my mistake I am glad it did not 
confuse the intent of my question and you were able to provide some really 
helpful suggestions below.

> 
> > My attempt is located here - https://gist.github.com/pjfoley/5989653
> 
> A word of advice: don't assume that just because people are reading your 
> 
> posts, that they necessarily will follow links to view your code. There 
> 
> could be all sorts of reasons why they might not:
> 
> * SNIP Justification *

> 
> Or some other reason. For best results, you should try to simplify the 
> 
> problem as much as possible, bringing it down to the most trivial, easy 
> 
> example you can, small enough to include directly in the body of your 
> 
> email. That might be one line, or twenty lines.
> 

In my defence I was trying to give some context for my problem domain.  The 
bottom of the original post (which you provided some suggestions on) had the 
simplified question.  I find that people are more likely to help if they don't 
think its just a *homework question* and that someone is genuinely trying to 
learn.

As I mentioned in the very first line of my email I am just starting to learn 
Python and was not even sure what I was supposed to be looking for.  Obviously 
I found the hammer straight away *BINGO*!  However in my defence when I was 
searching I did not have the necessary knowledge to even start looking in the 
right place.  For reference I started searching for slice's, splitting and 
separating.

I will look into the techniques and keywords you suggested and try your various 
suggestions.

Thanks for your pointers.

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


Re: Python Interview Questions

2012-07-09 Thread Peter
One of my favourite questions when interviewing - and it was 100% reliable :-) 
- "what are your hobbies?"

If the answer included programming then they were hired, if not, then they went 
to the "B" list.

In my experience, anybody who is really interested in programming will have it 
as a hobby (and is keen to learn even if they don't currently have the 
knowledge you require) - otherwise it is "just a job". Every job has a learning 
curve - whether it is just the particular domain or even a new language, the 
individual who sees programming as more "than a job" will come up to speed much 
faster and be more productive in both the short and long term.

Every programmer I have ever hired using this criteria worked out well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which Version of Python?

2012-09-11 Thread Peter
If your desire is to "learn" Python then I would stick to 2.7

My reasoning would be that there are still a significant number of packages 
that have not been ported to 3.x (and may never be ported). 

Not having looked at the changes in 3.x (so don't flame me! :-)), it would seem 
that anything you "learn" in 2.7 would be easily transferred "up" when and if 
you feel the need to go to 3.x, but in the meantime enjoy the better support of 
a greater range of packages that are still only 2.x compatible! i.e. learning 
(and using) features of 3.x could make it difficult to go "down" when/if you 
decide you really need to use a library that hasn't (and may never!) be ported 
to 3.x. For example, Graysons book on Python GUI programming is still one of 
the better Python GUI books (although very old now!) and it would steer you 
towards using the Pmw library - which may never be ported to 3.x. If you decide 
to use wxPython for your GUI work then I see that has support for 2.x only also.

So in this case, staying with the lower common denominator might be the better 
choice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused compare function :)

2012-12-06 Thread peter

On 12/06/2012 08:47 AM, Steven D'Aprano wrote:

On Thu, 06 Dec 2012 09:49:26 +0100, Bruno Dupuis wrote:


The point is Exceptions are made for error handling, not for normal
workflow.

That's certainly not the case in Python. Using exceptions for flow
control is a standard part of the language.

IndexError and StopIteration are used to detect the end of lists or
iterators in for loops.

GeneratorExit is used to request that generators exit.

SysExit is used to exit the interpreter.


There is nothing wrong with using exceptions for flow control in
moderation.



I hate when i read that for example:

 try:
 do_stuff(mydict[k])
 except KeyError:
 pass

(loads of them in many libraries and frameworks) instead of:

 if k in mydict:
 do_stuff(mydict[k])

Note that the performances are better with the latter.

Not so. Which one is faster will depend on how often you expect to fail.
If the keys are nearly always present, then:

try:
 do_stuff(mydict[k])
except KeyError:
 pass

will be faster. Setting up a try block is very fast, about as fast as
"pass", and faster than "if k in mydict".

But if the key is often missing, then catching the exception will be
slow, and the "if k in mydict" version may be faster. It depends on how
often the key is missing.


[...]

It depends also on the context, I'd be more 'permissive' a short script
than into a large program, framework, or lib, for the very reason it's
easy to know all code interactions.

In my coder life, i spent more time debugging silently swallowed
exceptions than logging abnormal behaviours.


That's fine. I agree with you about not silently swallowing errors. Where
I disagree is that you said "never ever", which is an exaggeration.
Remember that exceptions are not always errors.

Problem: take a list of strings, and add up the ones which are integers,
ignoring everything else.

Solution:

total = 0
for s in list_of_strings:
 try:
 total += int(s)
 except ValueError:
 pass  # Not a number, ignore it.


Why would you want to log that? It's not an error, it is working as
designed. I hate software that logs every little thing that happens, so
that you cannot tell what's important and what isn't.




Is perfectly right to use try catch for a flow control.
Just think in something more complex like this.

   try:
self._conn = MySQLdb.connect(host=host,
user=user,
passwd=passwd,
db=db)
except:
logging.info("Error de conexion con la base de datos")
inform(subject = 'Db down on app %s' % app, body=sbody)

Or maybe something like this.

try:
cursor.execute(sqli, data)
self._conn.commit()
except:
try:
self._conn.rollback()
cursor.execute(sqli, data)
self._conn.commit()
except Exception, e:
pass
# print e
# logging.info('ERROR en la insercion %s' % e)

This is pretty dumb, but is a valid example, on what you can do with try 
catch

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


Re: Confused compare function :)

2012-12-06 Thread peter

On 12/06/2012 10:58 AM, Chris Angelico wrote:

On Fri, Dec 7, 2012 at 12:33 AM, Thomas Rachel

wrote:

Am 06.12.2012 09:49 schrieb Bruno Dupuis:


The point is Exceptions are made for error handling, not for normal
workflow. I hate when i read that for example:

  try:
  do_stuff(mydict[k])
  except KeyError:
  pass

I would do

 try:
 value = mydict[k]
 except KeyError:
 pass
 else:
 do_stuff(k)

Why? Because do_stuff() might raise a KeyError, which should not go
undetected.

(Assuming first off that you meant "do_stuff(value)", not
"do_stuff(k)", in that last line)

That has quite different functionality, though. The original wouldn't
have called do_stuff at all if k is not in dict, behaviour which is
matched by both his EAFP and his LBLY. But your version, in the event
of a KeyError, will call do_stuff with the previous value of value, or
raise NameError if there is no such previous value. I don't think
that's intentional.

The only way around it that I can see is an extra condition or jump -
something like:

def call_if_present(mydict,k,do_stuff):
 """Equivalent to
 do_stuff(mydict[k])
 if the key is present; otherwise, does not call do_stuff, and
returns None."""
 try:
 value = mydict[k]
 except KeyError:
 return
 return do_stuff(value)

It'll propagate any other exceptions from the subscripting (eg
TypeError if you give it a list instead of a dict), and any exceptions
from do_stuff itself. But it's getting a bit unwieldy.

ChrisA
Ok, is seems like my example code, don't like :). Is ok, it was a poor 
example.

This a more complex example that create a python daemons process.
In these case you see the help of try catch. To watch an Operating 
system problem (80% of the cases), when the fork is created. Or  you can 
initialize a logging (in the catch statement)

and watch the log file with tail -f.


import sys, os
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid( )
# Perform second fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)
# The process is now daemonized, redirect standard file descriptors.
for f in sys.stdout, sys.stderr: f.flush( )
si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno( ), sys.stdin.fileno( ))
os.dup2(so.fileno( ), sys.stdout.fileno( ))
os.dup2(se.fileno( ), sys.stderr.fileno( ))

Or imagine that you are manage master-slave's connections (for examples 
to an ldap databse - or a monitor system tools), you can use try catch.
If all the server's are down, maybe you want to be inform about it, you 
can put a function to send a email to your account


In simple works try: catch is 'GOOD'.

ipserver = {"192.168.1.13": ["monitoreo", 22],
"192.168.1.18": ["usuarios-dns", 22, 53, 139, 389, 445, 
631, 3306, 4900, 8765],
"192.168.1.72": ["sistemas-ldap", 22, 80, 139, 389, 445, 
631, 3306, 4900, 8765],

"192.168.1.74": ["terminales", 22,139, 445, 389, 4900],
"192.168.1.80": ["backup", 22, 139, 445],
"192.168.1.1": ["router", 21, 22, 25, 80, 110, 143, 465, 3128],
"192.168.1.90": ["router", 5900]
}

def portstatus(self, **kwargs):
ports = kwargs.get("ports")
server = kwargs.get("server")
if len(ports) > 0:
logging.info("chequeando puertos %s" % server)
for a in ports:
try:
sock = socket()
sock.connect((server,a))
sock.close
except:
logging.info("informando errores en puerto %s" % a)
today = str(datetime.today())
subprocess.Popen("for a in $(seq 1 15); do beep; 
done", shell=True)
self.sendreport(ip=server, server=server, 
cuerpo="El puerto  %s esta caido en %s - %s" % (a, server, today), 
asunto="El puerto  %s esta caido en %s - %s" % (a, server, today))

else:
logging.info("no hay puertos que chequear")







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


Re: Problem with __str__ method and character encoding

2012-12-07 Thread peter

On 12/07/2012 11:17 AM, gialloporpora wrote:

Risposta al messaggio di gialloporpora :


This is the code in my test.py:


Sorry, I have wrongly pasted the code:


class msgmarker(object):
def __init__(self, msgid, msgstr, index, encoding="utf-8"):
self._encoding =encoding
self.set(msgid, msgstr)
self._index = index

def __repr__(self):
return ""

def __str__(self):
return u'msgid: "%s"\nmsgstr: "%s"' %(self.msgid, self.msgstr)

def isUntranslated(self):
return self.msgid==self.msgstr

def isFuzzy(self):
return self.msgstr[0:2]=="=="

def markFuzzy(self):
self.msgstr = "==%s" %(self.msgstr)
def set(self, msgid, msgstr):
if not(isinstance(msgid, unicode)): msgid = 
msgid.decode(self._encoding)
if not(isinstance(msgstr, unicode)): msgstr = 
msgstr.decode(self._encoding)

self.msgid = msgid
self.msgstr = msgstr

def setmsgstr(self, msgstr):
if not(isinstance(msgstr, unicode)): msgstr = 
msgstr.decode(self._encoding)

self.msgstr = msgstr

def getIndex(self):
return self._index
def getIndex(self):
return self._index








what do you meant whe you say 'pretty print' ??.

is you just want to print a object in a nice format, you can use pprint

from pprint import pprint

nasty_dict = { 'hellou': bybye,
.

Imagine that nasty_dict have many complex object. For pretty print in 
the python console you can do this:


pprint(nasty_dict).

Is you use ipython:

%page nasty_dict
--
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-10 Thread peter

On 12/10/2012 12:42 PM, andrea crotti wrote:

So I implemented a simple decorator to run a function in a forked
process, as below.

It works well but the problem is that the childs end up as zombies on
one machine, while strangely
I can't reproduce the same on mine..

I know that this is not the perfect method to spawn a daemon, but I
also wanted to keep the code
as simple as possible since other people will maintain it..

What is the easiest solution to avoid the creation of zombies and
maintain this functionality?
thanks


def on_forked_process(func):
 from os import fork
 """Decorator that forks the process, runs the function and gives
 back control to the main process
 """
 def _on_forked_process(*args, **kwargs):
 pid = fork()
 if pid == 0:
 func(*args, **kwargs)
 _exit(0)
 else:
 return pid

 return _on_forked_process
Ou. yo need to use something more advanced. This is the code from book 
('Unix Network Programing' - the python implementation)


import sys, os
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)
# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid( )
# Perform second fork.
try:
pid = os.fork( )
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)
# The process is now daemonized, redirect standard file descriptors.
for f in sys.stdout, sys.stderr: f.flush( )
si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno( ), sys.stdin.fileno( ))
os.dup2(so.fileno( ), sys.stdout.fileno( ))
os.dup2(se.fileno( ), sys.stderr.fileno( ))

Put this file and named daemon.py, then just for your program by calling 
import this file.


Like this.

from daemon import daemonize

def main():
  while True:
print 'I'm Alive :)'

if __name__ == '__main__':
daemonize(stdout='/var/log/run_time.log', stderr='/var/log/error.log')
main()

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


Re: forking and avoiding zombies!

2012-12-11 Thread peter

On 12/11/2012 08:47 AM, andrea crotti wrote:

Yes I wanted to avoid to do something too complex, anyway I'll just
comment it well and add a link to the original code..

But this is now failing to me:

def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
 # Perform first fork.
 try:
 pid = os.fork()
 if pid > 0:
 sys.exit(0) # Exit first parent.
 except OSError as e:
 sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
 sys.exit(1)

 # Decouple from parent environment.
 os.chdir("/")
 os.umask(0)
 os.setsid()

 # Perform second fork.
 try:
 pid = os.fork()
 if pid > 0:
 sys.exit(0) # Exit second parent.
 except OSError, e:
 sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
 sys.exit(1)

 # The process is now daemonized, redirect standard file descriptors.
 sys.stdout.flush()
 sys.stderr.flush()

 si = file(stdin, 'r')
 so = file(stdout, 'a+')
 se = file(stderr, 'a+', 0)
 os.dup2(si.fileno(), sys.stdin.fileno())
 os.dup2(so.fileno(), sys.stdout.fileno())
 os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == '__main__':
 daemonize(stdout='sample_file', stderr='sample')
 print("hello world, now should be the child!")


[andrea@andreacrotti experiments]$ python2 daemon.py
Traceback (most recent call last):
   File "daemon.py", line 49, in 
 daemonize(stdout='sample_file', stderr='sample')
   File "daemon.py", line 41, in daemonize
 so = file(stdout, 'a+')
IOError: [Errno 13] Permission denied: 'sample_file'

The parent process can write to that file easily, but the child can't,
why is it working for you and not for me though?
(Running this on Linux with a non-root user)
In the time when you fork the proccess you can't use relative path, is 
dangerous. You need to use absolute path's like this.


import os, sys

def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# Perform first fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError as e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)

# Decouple from parent environment.
os.chdir("/")
os.umask(0)
os.setsid()

# Perform second fork.
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, 
e.strerror))

sys.exit(1)

# The process is now daemonized, redirect standard file descriptors.
sys.stdout.flush()
sys.stderr.flush()

si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())


if __name__ == '__main__':
daemonize(stdout='/tmp/sample_file.log', stderr='/tmp/sample.log')
print("hello world, now should be the child!")
--
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread peter

On 12/11/2012 10:25 AM, andrea crotti wrote:

Ah sure that makes sense!

But actually why do I need to move away from the current directory of
the parent process?
In my case it's actually useful to be in the same directory, so maybe
I can skip that part,
or otherwise I need another chdir after..
You don't need to move away from the current directory. You cant use os 
to get the current work directory


stderrfile = '%s/error.log' % os.getcwd()
stdoutfile = '%s/out.log' % os.getcwd()

then call the daemon function like this.

daemonize(stdout=stdoutfile, stderr=stderrfile)
--
http://mail.python.org/mailman/listinfo/python-list


Re: forking and avoiding zombies!

2012-12-11 Thread peter

On 12/11/2012 10:57 AM, andrea crotti wrote:

where in [] I have the PID of the process.
In this suggested way I should use some other files as standard output
and error, but for that I already have the logging module that logs
in the right place..
It's not realy neccesary do use the stderr and stdout parameters, in 
fact the default value for those parameters are null ('/dev/null').

The functionality is like this.
All you print to stdout going to be in the stdout parameter of the 
daemon function, and the same thing for stderr.


Now my suggestion for you, is you already have initialize a "logging 
file", just use the logging module  to redirect informacion  what's is 
doing your forked  function, and use the stderr paramater of the daemon 
function to DEBUG errors in the forked function.

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


samba 4 release

2012-12-12 Thread peter

Hellou.

   Samba4 first release, with python interface for the internals api, 
and a implementation of the DC in python :).


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


Re: samba 4 release

2012-12-12 Thread peter

On 12/12/2012 02:38 PM, peter wrote:

Hellou.

   Samba4 first release, with python interface for the internals api, 
and a implementation of the DC in python :).


Viva la python

I forgot to put the link of the good news

https://www.samba.org/samba/history/samba-4.0.0.html

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


Re: Command Line Progress Bar

2012-12-26 Thread peter

On 12/26/2012 03:17 AM, Kevin Anthony wrote:

Hello,
I'm writing a file processing script(Linux), and i would like to have 
a progress bar.  But i would also like to be able to print messages. 
 Is there a simple way of doing this without implementing something 
like ncurses?


--
Thanks
Kevin Anthony
www.NoSideRacing.com 

Do you use Banshee?
Download the Community Extensions:
http://banshee.fm/download/extensions/



I use this tecnique to make a progress bar in the console.
You just need to understand, that a progress bar is a 
cross-multiplication http://en.wikipedia.org/wiki/Cross-multiplication.


import sys, time

def progressbar(value, total):
maspro = (100*value) / total
sys.stdout.write('\r[%s]%d%%' % ('#'*(maspro/10), maspro))
sys.stdout.flush()

for a in range(1, 1000):
progressbar(a, 100)
time.sleep(2)


You can't combine your progress bar with threading module



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


Re: New to python, do I need an IDE or is vim still good enough?

2012-12-27 Thread peter

On 12/27/2012 05:01 PM, mogul wrote:

'Aloha!

I'm new to python, got 10-20 years perl and C experience, all gained on unix 
alike machines hacking happily in vi, and later on in vim.

Now it's python, and currently mainly on my kubuntu desktop.

Do I really need a real IDE, as the windows guys around me say I do, or will 
vim, git, make and other standalone tools make it the next 20 years too for me?

Oh, by the way, after 7 days I'm completely in love with this python thing. I 
should have made the switch much earlier!

/mogul %-)
You going to create a war here. My honest advice, is just taste the 
different ides that are out there.


- emacs
- vi
- aptana
- eclipse
- pycharm
- wingide.
- etc
- etc.

I currently use emacs for everything.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart (Terminolgy): "Class"

2013-01-14 Thread Peter
Real mature lot of responses here guys - shows how much you have grown up.

Reading this thread looked more like observing a bunch of 3rd grader - somebody 
offers an opinion and all you can do is ridicule it?

Real mature - certainly gives Python a good name having followers like this...

But then I guess I will cop flack for this rejoinder too...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending a broadcast message using raw sockets

2013-01-22 Thread peter
Yes, raw sockets need admin privileges, I knew that. The app I'm writing runs 
as root so that's not a problem. It runs during the %pre script stage of a 
kickstart controlled install.

On Tuesday, January 22, 2013 1:58:07 PM UTC-8, Rob Williscroft wrote:
> Try 
> 
>   s = socket.socket( socket.AF_INET, socket.SOCK_RAW )
> 
> 
> 
> I tried this on windows and it needed admin privaleges to
> 
> run.
> 
> 
> 
> Rob.
> 
> --

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


Re: pySerial question, setting certain serial parameters [newbie]

2012-02-07 Thread Peter
On Feb 4, 11:47 pm, Jean Dupont  wrote:
> I need to set the following options I found in a Perl-script in Python for 
> serial communication with a device (a voltmeter):
>
> $port->handshake("none");
> $port->rts_active(0);
> $port->dtr_active(1);
>
> I have thus far the following  statements but I think it does not set the 
> above parameters correctly:
> import serial
> voltport='/dev/ttyUSB2'
> ser2 = serial.Serial(voltport, 2400, 8, serial.PARITY_NONE, 1,timeout=15)
>
> thanks
> Jean

My reading of the __init__ method documentations shows you should
have:

ser2 = serial.Serial(voltport, 2400, dsrdtr=True, timeout=15)

since the defaults for bytesize are EIGHTBITS (for which you use 8 -
wrong), parity is already default to PARITY_NONE (so this isn't
needed), stopbits defaults to STOPBITS_ONE (for which you use 1 -
wrong) and (assuming the Perl code "1" is to enable) dsrdtr=True
(xonxoff and rtscts both default to False).

Try that.




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


help with subclassing problem

2012-04-02 Thread Peter
I am attempting to subclass the date class from the datetime package. Basically 
I want a subclass that can take the date as a string (in multiple formats), 
parse the string and derive the year,month and day information to create a date 
instance i.e. 

class MyDate(datetime.date):
  def __init__(self, the_date):
# magic happens here to derives year, month and day from the_date
datetime.date.__init__(self, year, month, day)

But no matter what I do, when I attempt to create an instance of the new class, 
I get the error message:

Traceback (most recent call last):
  File "", line 1, in 
TypeError: Required argument 'year' (pos 1) not found


I have even created a class which doesn't include the argument I want to use 
but with default arguments i.e.

class MyDate (datetime.date):
  def __init__(self, year = 1, month = 1, day = 1):
datetime.date.__init__(self, year, month, day)

and get the same error message.

What am I doing wrong here? 

Thanks for any help,
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are there any instrumentation widgets for wxpython or tkinter?

2012-05-17 Thread Peter

Or wxPython is another good alternative. Download the demo and have a look at 
the widgets people have already used/created. I think there are some good 
choices for instrumentation (from memory).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Tkinter by John E Grayson

2012-05-17 Thread Peter
I have used Grayson's book - purchased and read many years ago now though.

I am only an occasional GUI programmer, but have recently moved away from 
Tkinter and ttk towards wxPython - mainly because I am very dissatisfied with 
the lack of widgets to choose from. (new from 2.7 on) ttk supposedly added to 
the basic TkInter kit but is extremely difficult to work out due to lack of 
documentation i.e. I quickly wanted to use styles and finding some easy 
documentation that explained how all that worked was impossible - despite 
searching the Internet for hours (perhaps I was just unlucky? :-)).

For learning wxPython I am using "wxPython in Action" by Noel Rappin and Robin 
Dunn.

Neither book is about learning Python though - they are both aimed at users who 
have at least a basic Python background and want to learn about the particular 
GUI toolkit in question.

Even though I am on my first wxPython GUI, I am extremely happy that I made the 
switch - I am already using basic wxPython widgets that were just not available 
under TkInter/ttk, creating a much more intuitive interface (IMO :-)) for my 
users.

Best of luck in your choices,
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Tix Combobox

2011-06-08 Thread peter
I'm writing some fairly simple code using a Tkinter GUI, and found I
wanted a Combo box.   As Tkinter does not provide one, I turned to
Tix, and struggled.  Extensive googling failed to turn up any python
specific documentation, and there was no obvious way to translate the
Tcl documentation.

Nothing worked, and usually fell over with the error message
_tkinter.TclError: unknown color name "{#c3c3c3}".  Googling this
error message seemed to suggest that this was a known bug, and that
there was no readily available fix for those of us who like
applications to work out of the box.

Is this correct? If so is there any other Tkinter based solution, or
do I need to learn a new GUI?

I'm using Python 2.6.1 under WindowsXP

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


Re: Wait for a keypress before continuing?

2011-08-17 Thread peter
Is there an equivalent to msvcrt for Linux users?  I haven't found
one, and have resorted to some very clumsy code which turns off
keyboard excho then reads stdin. Seems such an obvious thing to want
to do I am surprised there is not a standard library module for it. Or
have I missed someting (wouldn't be the first time!)

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


Re: Wait for a keypress before continuing?

2011-08-18 Thread peter
On Aug 17, 3:16 pm, Hans Mulder  wrote:
> On 17/08/11 10:03:00, peter wrote:
>
> > Is there an equivalent to msvcrt for Linux users?  I haven't found
> > one, and have resorted to some very clumsy code which turns off
> > keyboard excho then reads stdin. Seems such an obvious thing to want
> > to do I am surprised there is not a standard library module for it. Or
> > have I missed someting (wouldn't be the first time!)
>
> The quick and dirty way is to invoke stty(1) using os.system:
>
> import os
>
> def getpassword(prompt="Password: "):
>      try:
>          os.system("stty -echo")
>          passwd = raw_input(prompt)
>      finally:
>          os.system("stty echo")
>      return passwd
>
> Strictly speaking, os.system is deprecated and you should use
> the equivalent invocation of subprocess.call:
>
> import subprocess
>
> def getpassword(prompt="Password: "):
>      try:
>          subprocess.call(["stty", "-echo"])
>          passwd = raw_input(prompt)
>      finally:
>          subprocess.call(["stty", "echo"])
>      return passwd
>
> If you don't want to use an external process, use termios:
>
> import termios, sys
>
> def getpassword(prompt="Password: "):
>      fd = sys.stdin.fileno()
>      old = termios.tcgetattr(fd)
>      new = termios.tcgetattr(fd)
>      new[3] = new[3] & ~termios.ECHO          # lflags
>      try:
>          termios.tcsetattr(fd, termios.TCSADRAIN, new)
>          passwd = raw_input(prompt)
>      finally:
>          termios.tcsetattr(fd, termios.TCSADRAIN, old)
>      return passwd
>
> These functions work on any Posix system (including Mac OSX),
> but not on Windows.
>
> Hope this helps,
>
> -- HansM

This is very similar to my solution, which was to use stty turn off
keyboard echo, then repeatedly read sys.stdin.read(1) until a unique
keystroke had been defined. For example, the 'Insert' key seems to
return a sequence of four codes, namely 27, 91, 50, 126.  It works but
has two disadvantages which I have managed to live with:-

1. As character 27 is used to signal the start of a 'special' key
sequence, it cannot detect a single press of the Esc key. The
workaround is to detect a double press instead.

2. Some keys seem to return different sets of codes depending on the
circumstances.  For example, F1 returns 27,91,91,65 from the command
line, and 27,79,80 from a GUI window. I suspect there may be
variations between flavours of Linux too. The solution is to detect
all possibilities - so far I haven't found any overlaps.

Not pretty, but as I said it works. I know now not to spend time
looking further. Whilst there may be a historical reason for the
current situation, it would be a great convenience for amateur coders
like mayself if the gurus could devise a platform independent version
of mscvrt.

If anyone is interested in the code I can post it, but it's quite long
as it comprises multiple if statements to cover each combination.

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


ttk styles

2011-03-13 Thread Peter
Hi I'm struggling to get a good understanding of styles as used in
ttk. I have read the tutorial section on using styles but haven't been
able to solve this problem.

I am attempting to create a Checkbutton with the indicatoron=false
option. Using ttk the documentation is clear that you have to create a
custom style to achieve this behaviour. But the only "example" I have
been able to find on the Internet searches is written in Tcl i.e. here
is what I have found (quoted directly):

Here’s how you set it up: To achieve the effect of -indicatoron false,
create a new layout that doesn’t have an indicator:

style layout Toolbar.TCheckbutton {
  Toolbutton.border -children {
   Toolbutton.padding -children {
 Toolbutton.label
   }
  }
}

Then use style map and style default to control the border appearance:

style default Toolbar.TCheckbutton \
 -relief flat
style map Toolbar.TCheckbutton -relief {
  disabled flat
  selected sunken
  pressed sunken
  active raised

Hopefully somebody else in this group has "done" this and can post
their "solution"?

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


Re: ttk styles

2011-03-17 Thread Peter
No responses? Nobody with knowledge of modifying styles etc?

On Mar 14, 2:08 pm, Peter  wrote:
> Hi I'm struggling to get a good understanding of styles as used in
> ttk. I have read the tutorial section on using styles but haven't been
> able to solve this problem.
>
> I am attempting to create a Checkbutton with the indicatoron=false
> option. Using ttk the documentation is clear that you have to create a
> custom style to achieve this behaviour. But the only "example" I have
> been able to find on the Internet searches is written in Tcl i.e. here
> is what I have found (quoted directly):
>
> Here’s how you set it up: To achieve the effect of -indicatoron false,
> create a new layout that doesn’t have an indicator:
>
> style layout Toolbar.TCheckbutton {
>       Toolbutton.border -children {
>            Toolbutton.padding -children {
>                  Toolbutton.label
>            }
>       }
>
> }
>
> Then use style map and style default to control the border appearance:
>
> style default Toolbar.TCheckbutton \
>      -relief flat
> style map Toolbar.TCheckbutton -relief {
>       disabled flat
>       selected sunken
>       pressed sunken
>       active raised
>
> Hopefully somebody else in this group has "done" this and can post
> their "solution"?
>
> Thanks
> Peter

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


Re: ttk styles

2011-03-17 Thread Peter
Thanks for the link Malcolm, I'll have a look at it. What is
particularly interesting (at first glance), is that the author has
"mixed" Tkinter with ttk as it suited i.e. look at this line:

f1 = tkinter.Frame(nb, background="red")

If ttk was being used purely (from tkinter import *; from ttk import
*) then the "background" keyword is nolonger available/recognised and
the code would have to use ttk styles to change the colour - I find it
somewhat disappointing that the author felt this approach was
necessary as it tends to dilute the example by not keeping everything
purely ttk - modifying the style to change the background of the Frame
statements would have made it an even better example!

I will repost the answer if I can work it out using this example code
- thanks again! :-)

Peter

On Mar 18, 9:14 am, pyt...@bdurham.com wrote:
> Peter,
>
> Sorry I can't be of much help, but I share the same interest as you.
>
> There may be some teaser info here although I can't claim to understand
> the 
> technique.http://www.java2s.com/Open-Source/Python/3.1.2-Python/Demo/Demo/tkint...
>
> If you have any links/documentation to share, I would love to see what
> you've found so far.
>
> Malcolm

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


Re: value of pi and 22/7

2011-03-18 Thread peter
On Mar 17, 5:22 pm, Kee Nethery  wrote:
> My favorite approximation is: 355/113  (visualize 113355 split into two 113 
> 355 and then do the division). The first 6 decimal places are the same.
>
> 3.141592920353982 = 355/113
> vs
> 3.1415926535897931
>
> Kee Nethery

Or (more for fun than any practical application) try (2143/22)^(1/4) =
3.14159265268.

Other approximations I have seen are root(10) and 3.142.  This last
was especially popular at school, which for me was sufficiently long
ago to have used four figure log tables.

The Old Testament (1 Kings 7,23) says ... "And he made a molten sea,
ten cubits from the one brim to the other: it was round all about, and
his height was five cubits: and a line of thirty cubits did compass it
round about. ".  So pi=3.  End Of.








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


Re: ttk styles

2011-03-20 Thread Peter
Here is what I came up with - hopefully I have understood the process
correctly and therefore that the comments are correct :-)

I am not sure I have the color of the indicator when it is (de)pressed
correct, but to my eyes the color 'snow' looks like the same color
used with a Tkinter Checkbutton with indicatoron=false.

r = Tk()

s = Style()

# create a layout that excludes the indicator element
s.layout('NoIndicator.TCheckbutton',
 [('Checkbutton.border',
   {'children': [('Checkbutton.padding',
  {'children': [('Checkbutton.label',
{})]})]})])

# Now create(?) a 'setting' for the border appearance of the
checkbutton
s.theme_settings('default', {
'NoIndicator.TCheckbutton': {'configure': {'relief': ''}}})

# set the attributes of the 'setting' to provide the required
behaviour
s.map('NoIndicator.TCheckbutton',
  relief=[('disabled', 'flat'),
  ('selected', 'sunken'),
  ('pressed', 'sunken'),
  ('active', 'raised'),
  ('!active', 'raised')],
  background=[('selected', 'snow')])

button = Checkbutton(r,
 text='Test',
 style='NoIndicator.TCheckbutton')
button.pack()

r.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is "self"?

2005-09-23 Thread Peter
Terry Hancock wrote:

>On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote:
>  
>
>>I've long thought that Guido missed an opportunity by not choosing 
>>to use 'i' as the instance identifier, and making it a reserved 
>>word. For one thing, it would resonate with the personal pronoun 
>>'I', and so carry essentially the same meaning as 'self'.
>>
Not realy.

>> It could 
>>also be understood as an initialism for 'instance'.
>>
MUCH better then trying to make it refer to "i" as in "me", but still.

>>And, because it 
>>is shorter, the number of objections to its existence *might* have 
>>been smaller than seems to be the case with 'self' as the 
>>convention.
>>
>>
Humm... maybe. But would reap the fact that i does not have the same 
exact meaning of self.
With the word self, it is possable to change a feature of yourSELF, but 
try saying you changed a feature of "yourI", some internal logic in the 
programmers brain is going to go off, and if the programmer is tired and 
trying to finish something up but has that kind of internal confusion, 
as suttle as it may be, he will get burnt out and have to wait intill 
the next day.

>>And as a side benefit, it would make it impossible to use as a loop 
>>index a language feature that would be a huge selling point among a 
>>lot of experienced programmers. 
>>
>>
>
>  
>
You think thats a good thing? o.0.
I agree that sometimes you need to name your loop variables well, but 
sometimes you only need a simple, temp loop variable.

I would expect such an aprouch to be more likely to be found in intercal 
(http://www.catb.org/~esr/intercal/), rather then in Python.

>How exactly is that?  Anybody who uses "i" as a variable name for
>anything other than an innermost loop index is a sick and twisted
>code sadist.
>
>  
>
Agreed, though to say "code sadist" is a little hard don't ya think? ;)

>You'd prefer what? "count" or "kount" or 
>"i_am_an_innermost_loop_index_counter".
>I mean "explicit is better than implicit", right?
>  
>
>Maybe Fortran warped my brain, but I just don't see the benefit here.
>
Me ither.

I am no english professor, but isn't the word "i" usualy pointed at 
something you will, have, can, or can't do in english?
"me" or "self" or "this" or "my" or "cls" or "inst" are refering to just 
the object, nothing more, nothing less (except for "my" which is like 
referring to "something i own") and are much more human-comprehendable. 
IMHO.

>--
>Terry Hancock ( hancock at anansispaceworks.com )
>Anansi Spaceworks  http://www.anansispaceworks.com
>
>  
>

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


Re: parsing a date

2005-09-23 Thread Peter
Kalle Anke wrote:

>I want to parse a date string, for example '2005-09-23', and since I haven't 
>done this before I would like to ask what is the best way to do it.
>
>I've looked around and the dateutil seems to be what most people use, but 
>unfortunately I only get an empty file when I try to download it. I also 
>tried the standard modules and ended up with this
>
>import datetime
>from time import strptime
>
>d = '2005-09-23'
>w = strptime(d,'%Y-%m-%d')
>print datetime.date( w[0], w[1], w[2] )
>
Well, thats not _to_ bad.

>But I suspect there is a better way to do it??
>
>  
>
There is...

I would check out "strftime"
With strftime you could do something like this...

# --
print strftime("%Y-%m-%d")
# -

or if you wanted to get the time in the past or future you could do 
something like

# --
tm = time.localtime(time.time() + ((60 * 60) * 24))
print strftime("%Y-%m-%d", tm)
# -

Which gets the date of tommarow.

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


Re: How to decompile an exe file compiled by py2exe?

2005-09-24 Thread Peter
Leo Jay wrote:

>Thanks for all of your replies.
>
>but my problem is not how to decompile .pyo or .pyc files.
>
>i used py2exe to compile my source file `hjparser.py' into
>`hjparser.exe' and other files. but i deleted the `hjparser.py' file
>by misoperation.(of cause, i tried to recover, but failed)
>
>  
>
Have you tried downloading a file recovery tool? e.g. something here:
http://www.pcworld.com/downloads/collection/0,collid,1295,00.asp

If you havn't, you might want to try that.
I would recommend getting one for a floppy, though, as installing a 
program may overwrite the deleted data, making it nearly impossable to 
recover (at least without some kind of microscope to view the markings 
on the pins of your harddrive, but lets not get into that...).

>I opened the `hjparser.exe' file in UltraEdit(a hex editor), and found
>some partial statements and comments but not complete.
>
>so, my problem is i'm sure that the source code is in `hjparser.exe'
>but i don't know how to decompile the executable file `hjparser.exe'
>into `hjparser.py',
>  
>
Unfortuanatly i don't know how you would go about doing that.

>i don't care about how to decompile .pyo or .pyc files.
>
>  
>
Well, Python compiles .py into .pyc files when it runs them, so you may 
have a .pyc on your computer, that you didnt delete, so you may want to 
check into that, also.

>Thanks
>
>
>On 9/24/05, Ivan Voras <[EMAIL PROTECTED]> wrote:
>  
>
>>It is - py2exe embeds python bytecodes. It seems it does it in the
>>"library.zip" file (if I'm reading
>>http://starship.python.net/crew/theller/moin.cgi/Py2Exe correctly).
>>Bytecode files extracted should be decompilable to something resembling
>>original python code by a python decompiler (quick Googling finds
>>"decompyle": http://www.crazy-compilers.com/).
>>--
>>http://mail.python.org/mailman/listinfo/python-list
>>
>>
>>
>
>
>
>--
>Best Regards,
>Leo Jay
>  
>
HTH,
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling with basics

2005-09-25 Thread Peter
Jason wrote:

>A week ago I posted a simple little hi-score routine that I was using to 
>learn Python.
>
>I've only just managed to examine the code, and the responses that 
>people gave, and I'm now seriously struggling to understand why things 
>aren't working correctly.
>
>At present my code is as follows...
>
>import random
>import bisect
>
>class HiScores:
> def __init__(self,hiScores):
> self.hiScores=[entry for entry in hiScores]
>
> def showScores(self):
> for score,name in self.hiScores:
> score=str(score).zfill(5)
> print "%s - %s" % name,score
>
>
> def addScore(self,score,name):
> score.zfill(5)
> bisect.insort(self.hiScores,(score,name))
> if len(self.hiScores)==6:
> self.hiScores.pop()
>
> def lastScore(self):
> return self.hiScores[-1][0]
>
>def main():
> 
>hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')]
> 
>
> a=HiScores(hiScores)
> print "Original Scores\n---"
> a.showScores()
>
> while 1:
> newScore=str(random.randint(0,1))
> if newScore  > a.lastScore():
> print "Congratulations, you scored %s " % newScore
> name=raw_input("Please enter your name :")
> a.addScore(newScore,name)
> a.showScores()
>
>if __name__=="__main__":
> main()
>
>
>My first problem (lack of understanding of course) is that if I run the 
>above, I get an error saying:
>
> print "%s - %s" % name,score
>TypeError: not enough arguments for format string
>  
>
>Now I understand what it's saying, but I don't understand why.
>
>If I change the code to read:
>
>print "%s - %n" % name, score (thinking of course that ah-ha, score is 
>numeric) then I get the same error.
>
>The only way for the program to run is to simply have
>
>print name,score (or print score,name)
>  
>
This is because 'print' is accepting 'score' as a seperate argument, not 
the formatting, as you want it to.
Try 'print "%s - %s" % (name, score)'

>
>The final part that's simply not working correctly is that the entire 
>program isn't sorting the data.
>
>If I run the program and get a score of, say, 6789, then when I add my 
>name, nothing is entered.  I have changed the clause that deletes (pops) 
>the last array if the array count is 6 and seen what figures are being 
>entered into the array.
>
>Sure enough they are going in the array, and they are being sorted, but 
>they are only being sorted AFTER the 0 of the initial array creation.
>
>I'm pretty sure it's to do with comparing a string against an integer 
>but can't for the life of me see where to force the comparrison to check 
>against two integers.
>
>  
>
Humm. This is a harder problem. I will copy this text into JEdit to 
highlight the text and see if i cannot find the problem.

>Apologies for going over old ground and if I'm not understanding, I'm 
>getting there honest ;)
>
>  
>

HTH,
Peter

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


Re: Struggling with basics

2005-09-25 Thread Peter
Peter wrote:

>Jason wrote:
>
>  
>
>>A week ago I posted a simple little hi-score routine that I was using to 
>>learn Python.
>>
>>I've only just managed to examine the code, and the responses that 
>>people gave, and I'm now seriously struggling to understand why things 
>>aren't working correctly.
>>
>>At present my code is as follows...
>>
>>import random
>>import bisect
>>
>>class HiScores:
>>def __init__(self,hiScores):
>>self.hiScores=[entry for entry in hiScores]
>>
>>def showScores(self):
>>for score,name in self.hiScores:
>>score=str(score).zfill(5)
>>print "%s - %s" % name,score
>>
>>
>>def addScore(self,score,name):
>>score.zfill(5)
>>bisect.insort(self.hiScores,(score,name))
>>if len(self.hiScores)==6:
>>self.hiScores.pop()
>>
>>def lastScore(self):
>>return self.hiScores[-1][0]
>>
>>def main():
>>
>>hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')]
>> 
>>
>>a=HiScores(hiScores)
>>print "Original Scores\n---"
>>a.showScores()
>>
>>while 1:
>>newScore=str(random.randint(0,1))
>>if newScore  > a.lastScore():
>>print "Congratulations, you scored %s " % newScore
>>name=raw_input("Please enter your name :")
>>a.addScore(newScore,name)
>>a.showScores()
>>
>>if __name__=="__main__":
>>main()
>>
>>
>>My first problem (lack of understanding of course) is that if I run the 
>>above, I get an error saying:
>>
>>print "%s - %s" % name,score
>>TypeError: not enough arguments for format string
>> 
>>
>>Now I understand what it's saying, but I don't understand why.
>>
>>If I change the code to read:
>>
>>print "%s - %n" % name, score (thinking of course that ah-ha, score is 
>>numeric) then I get the same error.
>>
>>The only way for the program to run is to simply have
>>
>>print name,score (or print score,name)
>> 
>>
>>
>>
>This is because 'print' is accepting 'score' as a seperate argument, not 
>the formatting, as you want it to.
>Try 'print "%s - %s" % (name, score)'
>  
>
>  
>
>>The final part that's simply not working correctly is that the entire 
>>program isn't sorting the data.
>>
>>If I run the program and get a score of, say, 6789, then when I add my 
>>name, nothing is entered.  I have changed the clause that deletes (pops) 
>>the last array if the array count is 6 and seen what figures are being 
>>entered into the array.
>>
>>Sure enough they are going in the array, and they are being sorted, but 
>>they are only being sorted AFTER the 0 of the initial array creation.
>>
>>I'm pretty sure it's to do with comparing a string against an integer 
>>but can't for the life of me see where to force the comparrison to check 
>>against two integers.
>>
>> 
>>
>>
>>
>Humm. This is a harder problem. I will copy this text into JEdit to 
>highlight the text and see if i cannot find the problem.
>
>  
>
Correction: I will fix my apearently semi-broaken Python installation 
wich gives me undefined reference errors from math.h and then see if i 
cannot fix the problem. -.-

>>Apologies for going over old ground and if I'm not understanding, I'm 
>>getting there honest ;)
>>
>> 
>>
>>
>>
>
>HTH,
>Peter
>
>  
>
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Struggling with basics

2005-09-25 Thread Peter
Duncan Booth wrote:

>Jason wrote:
>
>  
>
>>My first problem (lack of understanding of course) is that if I run the 
>>above, I get an error saying:
>>
>> print "%s - %s" % name,score
>>TypeError: not enough arguments for format string
>>
>>Now I understand what it's saying, but I don't understand why.
>>
>>
>>
>
>The problem is precedence.
>
>  print "%s - %s" % name,score
>
>is equivalent to:
>
>  print ("%s - %s" % name),score
>
>not:
>
>  print "%s - %s" % (name,score)
>
>The % operator binds more tightly than the comma, so you need to put 
>parentheses around the argument to % (as in the last line above).
>  
>
Well said. :)

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


Re: Struggling with basics

2005-09-25 Thread Peter
Peter wrote:

> Peter wrote:
>
>> Jason wrote:
>>
>>  
>>
>>> A week ago I posted a simple little hi-score routine that I was 
>>> using to learn Python.
>>>
>>> I've only just managed to examine the code, and the responses that 
>>> people gave, and I'm now seriously struggling to understand why 
>>> things aren't working correctly.
>>>
>>> At present my code is as follows...
>>>
>>> import random
>>> import bisect
>>>
>>> class HiScores:
>>>def __init__(self,hiScores):
>>>self.hiScores=[entry for entry in hiScores]
>>>
>>>def showScores(self):
>>>for score,name in self.hiScores:
>>>score=str(score).zfill(5)
>>>print "%s - %s" % name,score
>>>
>>>
>>>def addScore(self,score,name):
>>>score.zfill(5)
>>>bisect.insort(self.hiScores,(score,name))
>>>if len(self.hiScores)==6:
>>>self.hiScores.pop()
>>>
>>>def lastScore(self):
>>>return self.hiScores[-1][0]
>>>
>>> def main():
>>>
>>> hiScores=[('1','Alpha'),('07500','Beta'),('05000','Gamma'),('02500','Delta'),('0','Epsilon')]
>>>  
>>>
>>>a=HiScores(hiScores)
>>>print "Original Scores\n---"
>>>a.showScores()
>>>
>>>while 1:
>>>newScore=str(random.randint(0,1))
>>>if newScore  > a.lastScore():
>>>print "Congratulations, you scored %s " % newScore
>>>name=raw_input("Please enter your name :")
>>>a.addScore(newScore,name)
>>>a.showScores()
>>>
>>> if __name__=="__main__":
>>>main()
>>>
>>>
>>> My first problem (lack of understanding of course) is that if I run 
>>> the above, I get an error saying:
>>>
>>>print "%s - %s" % name,score
>>> TypeError: not enough arguments for format string
>>>
>>>
>>> Now I understand what it's saying, but I don't understand why.
>>>
>>> If I change the code to read:
>>>
>>> print "%s - %n" % name, score (thinking of course that ah-ha, score 
>>> is numeric) then I get the same error.
>>>
>>> The only way for the program to run is to simply have
>>>
>>> print name,score (or print score,name)
>>>
>>>
>>>   
>>
>> This is because 'print' is accepting 'score' as a seperate argument, 
>> not the formatting, as you want it to.
>> Try 'print "%s - %s" % (name, score)'
>>  
>>
>>  
>>
>>> The final part that's simply not working correctly is that the 
>>> entire program isn't sorting the data.
>>>
>>> If I run the program and get a score of, say, 6789, then when I add 
>>> my name, nothing is entered.  I have changed the clause that deletes 
>>> (pops) the last array if the array count is 6 and seen what figures 
>>> are being entered into the array.
>>>
>>> Sure enough they are going in the array, and they are being sorted, 
>>> but they are only being sorted AFTER the 0 of the initial array 
>>> creation.
>>>
>>> I'm pretty sure it's to do with comparing a string against an 
>>> integer but can't for the life of me see where to force the 
>>> comparrison to check against two integers.
>>>
>>>
>>>
>>>   
>>
>> Humm. This is a harder problem. I will copy this text into JEdit to 
>> highlight the text and see if i cannot find the problem.
>>
>>  
>>
> Correction: I will fix my apearently semi-broaken Python installation 
> wich gives me undefined reference errors from math.h and then see if i 
> cannot fix the problem. -.-
>
Well, My Python2.4 may have a broken math module, but my Python2.3 only 
has a broken cPickle. *Kicks computer*.

Try changing pop() to pop(0) and it should work.
string.pop by default removes the last element appended to the list, you 
want the first, which is the oldest.

>>> Apologies for going over old ground and if I'm not understanding, 
>>> I'm getting there honest ;)
>>>
>>>
>>>
>>>   
>>
>>
>> HTH,
>> Peter
>>
>>  
>>
> Peter
>
>
>
HTH,
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: backreferences

2005-09-28 Thread Peter
Iain King wrote:

>Amy Dillavou wrote:
>  
>
>>Can someone help me with understanding how python uses backreferences?
>>I need to remember the item that was last matched by the re engine but i
>>cant seem to understand anything that I find on backreferences.  if I
>>want to access the last match do i use \number or is there something
>>else i have to do?
>>
>>heres part of my code:
>>renDate = re.compile("$((\d){4}-(\d){2}-(\d){2}))")
>>renDate.search(l)
>>if(exist.search(l) and str(lastmodDate) < \1): #i need help here with \1
>>
>>Thanks in advance
>>A.D
>>
>>
>
>I haven't had to use backreferences yet, so I don't know offhand how to
>go about it.  What I do know is that this online book is very useful:
>
>http://gnosis.cx/TPiP/
>
>
>Chapter 3 covers REs:
>
>http://gnosis.cx/TPiP/chap3.txt
>
>>From what I remember, in python you can use numbered backreferences (up
>to 99), or named ones.
>
>Iain
>
>  
>
This shows both named backreferences and indexed. In both the 
replacement and the searching.

(?Pdata) sets the value of a named backreference named name to the 
value of data (but can only be used in the pattern).

\NUMBER gets the value of a backreference by its index (can be used in 
the pattern or the replacement).

(?P=name) gets the value of a named backreference (but only in the pattern).

\g gets the value of a named backreference (but only in the 
replacement).

Example:

re.sub(r"""<(?PH[1-5]) style="(.*)">(?P.*)""",
r"""\g | <\1 style="\2">\3<\1>""",
"""abc"""
 )

HTH,
Peter

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


Re: Class Help

2005-10-01 Thread Peter
Ivan Shevanski wrote:

>To continue with my previous problems, now I'm trying out classes.  But I 
>have a problem (which I bet is easily solveable) that I really don't get.  
>The numerous tutorials I've looked at just confsed me.For intance:
>
>  
>
>>>>class Xyz:
>>>>
>>>>
>... def y(self):
>... q = 2
>...
>  
>
>>>>Xyz.y()
>>>>
>>>>
>Traceback (most recent call last):
>  File "", line 1, in ?
>TypeError: unbound method y() must be called with Xyz instance as first 
>argument
>(got nothing instead)
>
>
>So. . .What do I have to do? I know this is an extremley noob question but I 
>think maybe if a person explained it to me I would finally get it =/
>
>  
>
You have to create an instance of the class before it can be called. Ex:
class foo:
def bar(self):
print "Hello, World!"
foo().bar()

This is because foo is a reference to a classobj, however, when you call 
the class, it becomes an instance.

Ex:
 >>> type(foo)

 >>> type(foo())


When an instance is created it tells Python to pass the instance as the 
first argument (self).
Otherwise it gives it None or something similer. (Note that im not 100% 
sure about why it does'nt work, im just guessing from the way it _seems_ 
to work. I have read no documentation on this.

If you want it to work before you create an instance, then you can do 
that with
class foo:
@classmethod
def bar(self):
   print "Hello, World!"

or the older (but exactly the same):
class foo:
def bar(self):
   print "Hello, World!"
bar = classmethod(bar)

>thanks in advance,
>
>-Ivan
>
>  
>
HTH,
Peter

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


Re: how do you pronounce wxpython

2005-10-10 Thread Peter
I always pronounced it double-you-ex-python. I am almost positive this 
is the way it is pronounced.

Although the wxPyWiki seems to be pronounced wix-pee-wi-kee (as it says 
on the front page) so maybe it is pronounced wix-Python... you never know...

HTH,
Peter

Alex wrote:

>My native language is not English so I just wonder how you pronounce
>wxPython.
>
>vi-ex python
>double-you-ex python
>wax-python
>
>or something else
>
>Thanks
>
>  
>

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


Re: mod_python

2005-10-11 Thread Peter
deelan wrote:

>Python_it wrote:
>(...)
>  
>
>>But my problem is where I have to place te following code in de
>>httpd.conf?
>>
>>
>>AddHandler mod_python .py
>>PythonHandler mptest
>>PythonDebug On
>>
>>
>>Because al the tutorials write this. But where?
>>
>>
>
>try put it at the end of your http.conf file.
>
> >
> > If I try to put the code some where,
> > apache give the following message by testing the configure:
> > Multiple  arguments not (yet) supported
> > But what i have to change or replace.
>
>  
>
>just an idea, try:
>
>
>...
>
>
>because it sounds like apache parser gets confused
>with all those slashes.
>
>  
>
I could be wrong, but i think i read something about apache expecting 
you to use forward slashes instead of backslashes when i was using 
windows...
I seem to recall it being in the readme. ...?

>>I test with the next file:
>>
>>C:\Program Files\Apache Group\Apache2\htdocs\project\
>>mptest.py
>>
>>from mod_python import apache
>>
>>def handler(req):
>>   req.content_type = 'text/plain'
>>   req.send_http_header()
>>   req.write('mptest.py\n')
>>   return apache.OK
>>
>>Is this code enough for testing?
>>
>>
>>
>
>i believe so.
>
>also check this:
>"Getting mod_python Working"
><http://www.dscpl.com.au/articles/modpython-001.html>
>
>  
>
HTH,
Peter

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


Re: my array subset method could be improved?

2005-10-14 Thread Peter
Jim O'D wrote:

>Hi all
>
>I have an array a=array([2,3,1]).
>
>I want to extract an array with all the elements of a that are less than 0.
>
>Method 1.
>new = array([i for i in a if i < 0])
>
>Method 2.
>new = a[nonzero(a<0)]
>
>I'm using Numeric arrays but can't seem to find a function that does this.
>
>Am I missing a more obvious way to do it quickly?
>
>Thanks
>
>Jim
>  
>
You could use filter (which is planned to be removed in Py3000). E.g. 
"array(filter(lambda x: x < 0, (-1, 2, -4, 5, 55, 9, -73, 5)))"

I tend to like "array(i for i in (-1, 2, -4, 5, 55, 9, -73, 5) if i < 
0)" better though. (And its even shorter).

HTH,
Peter

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


Re: difference after remove

2005-10-24 Thread Peter
Shi Mu wrote:

>Is there any difference if I remove the '/'
>  
>
I will assume you mean "\", not "/". ;)

>from the following statement?
>intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\
> [1,2,5,3,9,1,1,1,9,1],\
> [0,0,5,1,1,1,9,7,7,7]]
>print intMatrix2
>  
>
>I removed one '\' and it still works.
>So what is the use of '\'?
>  
>
Python normaly executes a statement as soon as a new line is given.

A backslash is for "line continuation", it tells Python to ignore the 
new line (instead of executing the current line as it would normaly).
If line-continuation is used in a string it will also ignore the new 
line (handy for when the theres to much on the line already but you 
don't want to break the string into two peices).

In some situations (inside functions calls, tuples, lists) this is not 
needed.


 Some examples of using line-continuation

# -
## Example 1

# With line-continuation:
 >>> print "a"\
... "b"\
... "c"
abc

# Without line-continuation:
 >>> print "a"
a
 >>> "b"
'b'
 >>> "c"
'c'

# ---
## Example 2

# With line-continuation:
 >>> print "Hello, \
... World!"
Hello, World!

# Without line-continuation:
 >>> print "Hello,
  File "", line 1
print "Hello,
 ^
SyntaxError: EOL while scanning single-quoted string
 >>> World!"
  File "", line 1
World!"
 ^
SyntaxError: invalid syntax

# -
## Example 3

# With line-continuation:
 >>> print """Hello, \
... World!"""
Hello, World!

# Without line-continuation:
 >>> print """Hello,
... World!"""
Hello,
World!

# -
## Example 4

# With line-continuation:
 >>> [1,\
... 2,\
... 3]
[1, 2, 3]

# Without line-continuation:
 >>> [1,
... 2,
... 3]
[1, 2, 3]

 >>>

 / End examples 

HTH,
Peter

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


Re: How to avoid "f.close" (no parens) bug?

2005-11-13 Thread Peter
o wrote:
> plez send me
>  
> 

First off, please explain what you are talking about better next time.

Second, What on earth are you talking about?

"f" is a file object, correct?

Are you trying to close a file by typing f.close or is the file closing 
when you type f.close?

If you are trying to close a file with f.close without parenthasies, 
then i _realy_ hope that this did not work, as f.close is nothing but a 
class method and should be treated like one except when called.

You may want to check out the Python tutorial at python.org 
http://docs.python.org/tut/tut.html

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


Re: Why is "if fileitem.file:" (almost) never false?

2005-11-17 Thread Peter
I think:

   form = cgi.FieldStorage()
   fileitem = form["userfile"]
   if fileitem.filename:
 data = form.getfirst("userfile")
 if data:
  #do somethinfg with it


FieldStorage objects always have a filename attribute which is  the
filename that the user used to upload the file or '' (maybe None) when
the FieldStorage object was not created for  a File upload. The
getfirst call returns the data of the file, but you need to access the
FieldStorage object directly forthe filename (as you did).

HTH

Peter


mark wrote:
> How do I detect that a particular form element is a file upload or if
> the file upload has worked?
>
> In the Python cgi module documentation I found suggested code...
>
> form = cgi.FieldStorage()
> fileitem = form["userfile"]
> if fileitem.file:
> # It's an uploaded file; count lines
>
>
> I've tried something like this in a test script and fileitem.file
> evaluates to true when form element "userfile" is just a text b
ox in
> the web page. When "userfile" is a type="file" it evaluates true when I
> select a real file to upload and when I manually type in a false path
> to a file that doesn't exist. When I do upload a file, the script
> correctly prints out the file contents (fileitem.value) so the upload
> does work OK.
>
> It seems that provided there's a form element called "userfile" then
> fileitem.file evaluates to true provided the form has
> enctype="multipart/form-data" (it doesn't matter if the file upload
> works or if the form element is not type="file").
>
> When I tried different forms without the enctype then fileitem.file
> evaluated to false when userfile was either type="text" or type="file".
>
> My conclusion is that if fileitem.file: detects enctype of form rather
> than if a particular element is a file upload. How do I detect that a
> particular form element is a file upload or if the file upload has
> worked?
>
> My best suggestion (but I'd like to hear your views) is to use:
> if fileitem.filename and len(fileitem.value):
># It's an uploaded file
>
> When the form element userfile is just a text box or the form lacks the
> enctype then the filename attribute evaluates to false. When I supply
> an incorrect file path to the file form element the upload fails so
> len(fileitem.value) evaluates to false. When I upload a real file, both
> fileitem.filename and len(fileitem.value) evaluate to true.
>
> If I upload a real file that's empty then fileitem.value is an empty
> string so len(fileitem.value) evaluates to false which is not quite
> right (an empty file is an obscure test but it is a valid file to
> upload).
>
> Any suggestions for improvements would be gratefully received.
>
> Thanks
>
> Mark
>
> PS if it's relevant, I'm using Windows2000, Python 2.3.2, the shebang
> includes -u, Apache 2.0.42 and Firefox 1.0.4.

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


JPEG decoder not available in PIL

2005-12-06 Thread Peter
I have a problem which seems to come up from time to time but I can't
find anything relevant in the archives.  I have used PIL v1.1.5 with no
problem on Windows for some time but now wish to put it on Linux (Suse
Linux v10.0). I obtained and built the JPEG libraries (jpeg-6b) without
any problem. The tests for the installation work fine. I built Python
2.4.2 from the sources but with no special options, just 'out of the
box'. This works fine. PIL built as it should but the selftest.py fails
with the  ‘'decoder jpeg is not available'’ message (the other 54
tests are OK). Other images are opened and shown with xv, no problem. I
think that there is something wrong with the libraries or the way they
linked.  

At the last moment I managed to solve this problem and I hope it is
worth supplying the details here. First there is a file in the install
directory libImaging/Jpeg.h which has a line:

#include "jpeglib.h"

but there is no such header file. On my system I put:

#include "/usr/local/include/jpeglib.h"

 which is where the JPEG installation put the include files for the
library. With this change all 55 tests passed successfully. Then I
copied the PIL library from the installation directory where it was
built to the Python site-packages location. And then everything worked.
For some reason it was not enough to do python setup.py install but
this is probably an artifact of previous failures.
 
 Hope this helps someone ...
 
 Peter

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


Curses on Windows

2005-02-06 Thread Peter
Last November I posted a message asking for advice on using simple
screen handling techniques under Windows.  Since then I have been
occupied with family / job /Christmas /living  and trying to
understand curses under linux (it works, seems very complex, sure I'm
missing something ...).  Only now am I returning to my original query.

One reply (in fact the only reply - thanks Tim Golden) suggested I
look at http://flangy.com/dev/python/curses/

Just tried that and got the message

"You don't have permission to access
/dev/python/curses/files/wcurses-0.1-py2.4.zip on this server."

any ideas why I can't access it - or any alternative URL's, or indeed
any other suggestions at all!  Grateful for any reply.

The email address is the one I registered under Google, and is now
defunct!

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


relative import packages/modules workaround

2005-07-11 Thread peter
Hello all,

I've read all the posts concerning relative imports of modules and I am
glad I saw some consensus on a syntax.
At this moment I am however bound to python 2.3.

Does anyone know a good workaround (or a library) which can achieve a
relative import for this python version

kind regards

Peter

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


Re: relative import packages/modules workaround

2005-07-12 Thread peter
hmm,

it seems to be less trivial than you mentioned...

hopefully this will be introduced fast in python

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


distutils package_dir newbie

2005-08-03 Thread peter
Hello all,

I've have following problem

the layout of my program is the following:
setup.py
project_dev/__init__.py
project_dev/someModule.py

now I want to make a source-installer so python setup.py install will
give the following directory stucture:

site-packages/project_user/__init__.py
site-packages/project_user/someModule.py

notice the namechange from project_dev to project_user

how do I achieve a namechange from project_dev to project_user???

I've tried several different versions of command package_dir options in
the setup function:
package_dir = {'project_user': 'project_dev'}
also package_dir = {'project_dev':'project_user'}
both without any success.  (relatively unintuitive option this is)

Can anybody give the correct way to achieve a directory-renaming when
creating an installer?

kind regards

Peter

keywords: renaming, directory, sdist, distutils, package_dir

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


Re: distutils package_dir newbie

2005-08-03 Thread peter
thx for answering is such short notice.

I recieve the following error when I use your setup:
error: package directory 'project_user' does not exist
(the complete error is added at the end of this document)

I'm using python 2.3.5 (build by activeState) based on python 2.3.5

Do you have an idea what could have happened here?

kind regards

Peter

ps.
complete error
running sdist
warning: sdist: missing required meta-data: url
warning: sdist: missing meta-data: either (author and author_email) or
(maintain
er and maintainer_email) must be supplied
warning: sdist: manifest template 'MANIFEST.in' does not exist (using
default fi
le list)
warning: sdist: standard file not found: should have one of README,
README.txt
error: package directory 'project_user' does not exist

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


Re: distutils package_dir newbie

2005-08-03 Thread peter
hello Robert

I've tried your setup.py file and now it seems to work...
I've made the following fault in the setup:
I did use:
setup(..., packages = ['project_dev'], ...) instead of the correct one:
setup(..., packages = ['project_user'], ...)

you have been a great help

Peter

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


Sequential XML parsing with xml.sax

2005-08-23 Thread peter
Hi hi.

I'm trying to do sequential decompression of a bzipped XML file and
feed it to a SAX parser with the following code.

remotefh = urllib.urlopen('file:///home/peter/catalog.rdf.bz2')
decompressor = bz2.BZ2Decompressor()
handler = CatalogueDocumentHandler(sys.stdout)
chunksize = 2048
data = remotefh.read(chunksize)
while data != '':
out = decompressor.decompress(data)
if out != '':
xml.sax.parseString(out, handler)
data = remotefh.read(chunksize)

This fails with the first chunk of decompressed data passed to
xml.sax.parseString. I'm suspecting because it's an incomplete fragment
of XML. I've tried with a number of different chunk sizes, putting the
break in different places, but it always fails on the first call. For
reference, the traceback looks like:

xml.sax.parseString(out, handler)
  File "/usr/lib/python2.4/site-packages/_xmlplus/sax/__init__.py",
line 47, in parseString
parser.parse(inpsrc)
  File "/usr/lib/python2.4/site-packages/_xmlplus/sax/expatreader.py",
line 109, in parse
xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib/python2.4/site-packages/_xmlplus/sax/xmlreader.py",
line 125, in parse
self.close()
  File "/usr/lib/python2.4/site-packages/_xmlplus/sax/expatreader.py",
line 226, in close
self.feed("", isFinal = 1)
  File "/usr/lib/python2.4/site-packages/_xmlplus/sax/expatreader.py",
line 220, in feed
self._err_handler.fatalError(exc)
  File "/usr/lib/python2.4/site-packages/_xmlplus/sax/handler.py", line
38, in fatalError
raise exception
xml.sax._exceptions.SAXParseException: :15132:63: no element
found

(line 15132 is the last, incomplete line feed to parseString. FWIW,
it's:
  Searchlights o
)

The API reference isn't clear on whether parseString can only handle
discrete bits of valid XML, or if it's designed to be called in this
way. So I'm not sure if I'm misusing the function, or if I've done
something else wrong.

Any pointers?
Thanks,
-- 
Pete

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


Re: Sequential XML parsing with xml.sax

2005-08-23 Thread peter
Hi.

Fredrik Lundh wrote:
> [EMAIL PROTECTED] wrote:
>
> > The API reference isn't clear on whether parseString can only handle
> > discrete bits of valid XML
>
> the documentation says that "parse" expects an XML document,
> and that "parseString" is the same thing, but parses from a buffer.

OK, so it sounded a lot more ambiguous at 4am. :-)

> it's probably easier to pass a BZ2File instance to "parse",

It is easier to retrieve a remote file, and decompress and parse as
separate steps. But I've been wondering if it would be faster / more
efficient to do it without caching.

> but if you
> insist on doing incremental SAX parsing, the IncrementalParser class
> might be what you need:

That'll do the trick nicely. Thanks.

Cheers,
-- 
Pete

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


adding new functionality to a function non-intrusively!

2005-02-16 Thread peter
Hello all,

Recently I've started to refactor my code ...
I would like to add extra functionality to a function !non-intrusively!
(not rewriting the old code is really important)
How can I achieve this?

Thus I start with an old function named fA.
I would like to add extra functionality to fA.
Essentially this gives a new function fA which can call the old
function fA

thanks a lot for reading so far

Peter

ps.
following idea does not work!
# fA = old fA, already defined
def tempFunc(*args):
   # do something with fA
   return
fA = tempFunc # gives infinite loop, recursive mails
# this example is explained in more detail in other mail called:
"renaming 'references' to functions gives recursive problems'

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


renaming 'references' to functions can give recursive problems

2005-02-16 Thread peter
Hello all,

Recently I've started to refactor my code ...(I'm using python 2.3.4)
I tried to add extra functionality to old functions non-intrusively.
When I used a construct, which involves renaming functions etc... I
came across some recursive problems.  (a basic construct can be found
under the section BASIC CODE)

These problems do not occur when renaming objects.  (see section EXTRA
CODE)
My question now is:
I do not know the underlying idea of functions.  Is this the way they
should behave? Or should they work the same way as objects do?
(My preferences goes to this last option)

BASIC CODE:
---
def fA(input): # starting point: function named fA
return input

def newFA(input): # new function with added functionality
#does something extra with a!
return fA(input)
fA = newFA
 # this should allow to add functionality without
 # breaking older code which uses the name fA!
fA() # execute fA()

problem: you get...
File "recursivemethods.py", line 7, in newFA
return fA(input)
RuntimeError: maximum recursion depth exceeded

when using objects this problems does not occur...
EXTRA CODE:

PYTHON-CODE   # REMARKS
referenceA = SomeObject() #  referenceA -> SomeObject()
  #   references to the memory space of
  #  some object
referenceB = referenceA   #  referenceB -> SomeObject()
  #   is also a reference to ...
referenceA = referenceB   #  referenceA references to SomeObject()

# now for functions!
fA = function #  fA references to memory space
  #  of a function

def newFA(input): #  newFA references to a function
   return fA(input)   #  which holds a reference to fA.
  #  Notice the important difference with objects!
  #  newFA holds a reference to the reference fA
  #  When using object you reference to
  #  the memory space of fA!!!
fA = newFA
fA()  # recursive problems!!!
--

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


Re: adding new functionality to a function non-intrusively!

2005-02-16 Thread peter
Hello

I indeed also rely on your idea.
My problem however is: is has to be non-intrusively in both ways.

In your example, it would indeed not break the old code which relies on
myfunction
but my problems is: I also do not want to change the code of the
'before' myfunction.

so my problem in fact  is:
BEFORE:
def myfunction(a,b):
  return (a+b)
AFTER:
def myfunction(a,b, op="add"):
   if (op == "add"):
  # some function which calls the old code for myfunction

kind regards

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


Re: adding new functionality to a function non-intrusively!

2005-02-16 Thread peter
thx a lot for the information on decorators

this will be very usefull... (sounds like a little step towards aspect
orientated programming,:) )

Because I use libraries which rely on boost-python I  can not jump into
python 2.4

but I understand the main idea and can also use it in python 2.3
(it will only cost a little bit more extra coding)

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


Re: renaming 'references' to functions can give recursive problems

2005-02-16 Thread peter
see the topic:
 adding new functionality to a function non-intrusively! and decorators
if you want to add functionality to a function!

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


Re: renaming 'references' to functions can give recursive problems

2005-02-16 Thread peter
Hello, nice solution:
but it puzzles me :)

can anyone tell me why
---correct solution
def fA(input):
  return input

def newFA(input, f= fA):
   return f(input)

fA = newFA

is correct and:
-infinite loop-

def fA(input):
  return input

def newFA(input):
   return fA(input)

fA = newFA

gives an infinite recursive loop?

kind regards

Peter

Antoon Pardon wrote:
> Op 2005-02-16, peter schreef <[EMAIL PROTECTED]>:
> > Hello all,
> >
> > Recently I've started to refactor my code ...(I'm using python
2.3.4)
> > I tried to add extra functionality to old functions
non-intrusively.
> > When I used a construct, which involves renaming functions etc... I
> > came across some recursive problems.  (a basic construct can be
found
> > under the section BASIC CODE)
> >
> > These problems do not occur when renaming objects.  (see section
EXTRA
> > CODE)
> > My question now is:
> > I do not know the underlying idea of functions.  Is this the way
they
> > should behave? Or should they work the same way as objects do?
> > (My preferences goes to this last option)
> >
> > BASIC CODE:
> >
---
> > def fA(input): # starting point: function named fA
> > return input
> >
> > def newFA(input): # new function with added functionality
> > #does something extra with a!
> > return fA(input)
> > fA = newFA
> >  # this should allow to add functionality without
> >  # breaking older code which uses the name fA!
> > fA() # execute fA()
>
> Try this:
>
> def fA(input):
>   return input
>
>
> def newFA(input, f= fA):
>   return f(input)
> 
> fA = newFA
> 
> -- 
> Antoon Pardon

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


Re: renaming 'references' to functions can give recursive problems

2005-02-16 Thread peter
brain reset and understood 

thx a lot for all your answers

Peter

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


Re: adding new functionality to a function non-intrusively!

2005-02-16 Thread peter
indeed it does,  so basically everything works except my original
solution:

def myfunction(a,b):
return a+b

def _myfunction(a,b):
   return myfunction(a,b)
myfunction = _myfunction

oh well, it was enough to puzzle my tiny brain

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


Re: Text To Speech with pyTTS

2005-03-03 Thread Peter
I released a new version of the Windows installer for Python 2.3 that
includes the missing _TTSFast.pyd file.


Peter Hansen wrote:
> Mike P. wrote:
> > I was wondering if anyone has had any luck with the python text to
speech
> > (pyTTS) module available on Sourceforge:
> > http://sourceforge.net/projects/uncassist
>
> I saw the following blog entry by Joey deVilla:
>
http://farm.tucows.com/blog/Platforms/Windows/_archives/2005/1/19/266813.html
>
> and immediately tried it out.  All I did was download the
> PyTTS package for Python (2.4, not 2.3), and install it,
> then ran Joey's sample above.  It worked as advertised.
> This was on Windows XP SP2.
> 
> -Peter

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


How to remove packages - wxPython

2004-12-11 Thread Peter
Linux kernel 2.6.9
Slackware 10
Python version 2.3.4
wxPython version 2.4.2.4

I compiled and installed wxPython.

There is no uninstall script that I can find for the py components. The
library component has a make uninstall.

What is the proper way to uninstall packages? I searched everywhere, but
there seems to be no clearcut explanation.

Can I just remove the site-package directories it created? Or is there a
central config file for python?

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


Re: How to remove packages - wxPython

2004-12-11 Thread Peter
Peter Hansen wrote:

> Peter wrote:
>> Linux kernel 2.6.9
>> Slackware 10
>> Python version 2.3.4
>> wxPython version 2.4.2.4
>> 
>> I compiled and installed wxPython.
>> 
>> There is no uninstall script that I can find for the py components. The
>> library component has a make uninstall.
>> 
>> What is the proper way to uninstall packages? I searched everywhere, but
>> there seems to be no clearcut explanation.
>> 
>> Can I just remove the site-package directories it created? Or is there a
>> central config file for python?
> 
> Generally speaking, just removing the subfolder(s) from site-packages
> will completely remove an extension.  Some few extensions will also
> create a .pth file in the site-packages folder, so check for that
> as well.  No doubt there are exceptions, but I believe this will
> cover 95% of the cases.
> 
> -Peter

That's what I thought. Just wanted to be sure. I think this program actually
created two separate site-packages folder, wxPython and wx. I need to check
the install script and see what was doing.

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


uninstalling python27 killed vim (actual issue was more complicated and involves Mercurial)

2014-01-28 Thread Peter
I'm posting this information to help others who are transitioning from 
Python 2.x to Python 3.x and are using Vim and Mercurial on Windows.


BACKGROUND

Old workstation configuration: 32-bit Windows XP/SP3, Python 2.7.6 and 
3.3.3, Mercurial 2.8.2, PATH contained Python before Mercurial, dual 
boot with Slackware 14.0


New workstation configuration: 64-bit Windows 7/SP1, 64-bit Python 
3.3.3, 64-bit Mercurial 2.8.2, PATH contained Python before Mercurial, 
dual boot with Slackware64 14.1


Early last year, I ported dozens of Python 2.7 tools that I wrote to 
automate various development tasks to Python 3 (via 2to3 script and 
testing).  After the ports were completed, I had my colleagues replace 
their Python2 installations with Python3.  We quickly uncovered/fixed a 
few issues (mostly related to Unicode) that I missed in my initial 
testing.  We've been happily running the Python3 versions for months 
now, but I've been reluctant to remove Python27 from my old (soon to be 
retired) workstation.


PROBLEM

Yesterday, I finally decided to say goodbye to Python27 on Windows and 
uninstalled it from my old workstation.  A little while later, I noticed 
that vim no longer worked.  Gvim.exe silently failed and vim.exe failed 
with the following error:


ImportError: No module named site

After reading the relevant vim documentation 
(http://vimdoc.sourceforge.net/htmldoc/if_pyth.html#python-dynamic) and 
doing a few Google searches, I decided to run vim under windbg to see 
what was actually going on.  Windbg showed that vim loaded the 
python27.dll from my Mercurial installation just before exiting.  A 
quick look inside Mercurial's library.zip file showed that the site.py 
module was not included.  OK, so now things were starting to make sense.


WORKAROUND

I took Mercurial out of the PATH, which returned vim to working order. 
I then wrote the following two line hg.bat script and copied it to a 
directory include in the PATH:


@echo off
"C:\Program Files\Mercurial\hg.exe" %*

With this workaround, both vim and hg appear to be once again working on 
the old workstation.


64-BIT WINDOWS

As the vim for Windows package I installed is a 32-bit application, I 
didn't have this issue on 64-bit Windows using 64-bit Mercurial. 
However, I believe the same issue would occur if 32-bit Mercurial is 
used on 64-bit Windows.


Hopefully this information is useful to other Python, Vim, and Mercurial 
users.


Peter Santoro
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python GUI?

2013-09-12 Thread Peter
I stuck with Tkinter combined with PMW for a very long time, but the lack of 
extra widgets finally drove me to look elsewhere.

I tried PyQT but didn't have a good experience. I can't remember details, but 
things just seemed to have little "gotchas" - which the mailing list were very 
helpful with sorting out, but I found it frustrating to keep asking for help 
over little items of unexpected behaviour.

I have not tried PyGTK so cannot comment.

I finally decided on wxPython - with my basis of Tkinter (graysons book) it was 
quite easy to pick up and run with. The wxPython book is quite good and helps 
get started and using it. I would suggest if you buy and read that, then you 
will no longer find wxPython difficult to get started with.

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


use of subprocess module inside generator

2015-05-13 Thread Peter


I'm using Python 3.4.3 on Windows 7 (with latest patches) to develop a 
sqlcmd module for accessing SQL Server (via Microsoft's sqlcmd.exe).  My 
goal is to develop a 100% Python 3 module that's easy to use, flexible, 
and by design shifts the majority of future SQL Server Python database 
access maintenance to Microsoft.  So far, I've successfully and quickly 
converted a few of my Python pyodbc applications/tools to use this new 
module.  However, I recently ran into an apparent Python issue which 
cost me a few hours to diagnose and work around.


I'm hoping that someone might know what the root cause of my issue was. 
 Perhaps I've hit a bug/restriction with Python generators?


My original generator function looked like this:

def _raw_data(cl, stdout, *, opath=None, timeout=timeout):
stdout = subprocess.check_output(cl, universal_newlines=True, 
timeout=timeout)


if opath is None:
for line in stdout.splitlines():
yield line.strip()
else:
with open(opath) as f:
for line in f:
yield line.strip()

The above function appeared to work fine, if the command line directed 
sqlcmd.exe to send its output to stdout.  However, if the command line 
directed sqlcmd.exe to send its output to a file, 
subprocess.check_output would never be called when next was called on 
the returned generator.  I verified this behavior with print statements 
inside my code, as well as, inside the subprocess module.


My work around was to simply move the call to subprocess.check_output 
outside of the generator function (see below) to its caller (a 
non-generator function).  With this minor change, everything appears to 
work as expected.  OK, so am I missing something here?


def _raw_data(stdout, *, opath=None):
if opath is None:
for line in stdout.splitlines():
yield line.strip()
else:
with open(opath) as f:
for line in f:
yield line.strip()

Thank you in advance for your assistance.

Peter Santoro
--
https://mail.python.org/mailman/listinfo/python-list


use of subprocess module inside generator

2015-05-13 Thread Peter

Gary,

Thank you for the response.  I made a small typo in my original post, 
which you correctly picked up.  My original generator actually did not 
have the stdout parameter (see below).  Only the new generator has this 
parameter, as it's now being passed into the generator from the caller's 
execution of subprocess.check_output.


def _raw_data(cl, *, opath=None, timeout=timeout):
stdout = subprocess.check_output(cl, universal_newlines=True, 
timeout=timeout)


if opath is None:
for line in stdout.splitlines():
yield line.strip()
else:
with open(opath) as f:
for line in f:
yield line.strip()


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


Re: python string, best way to concat

2014-08-28 Thread peter
I used to struggle with the concept of ''.join(('hello ','world')) - it seemed 
so convoluted compared with the intuitive 'hello '+'world', and I could never 
remember the syntax.  Also, for the strings I was generally using the 
performance penalty was infinitesimal, so I was just adding complexity for the 
sake of the abstract concept of a more 'pythonic' style.

Obviously this isn't going to change, but for concatenating short strings a and 
b is there any practical reason to avoid a+b?

Peter

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


Reading screen width of a Tkinter widget.

2011-10-13 Thread peter
I recently had a problem while trying to set up a Tkinter Canvas
widget as a progress bar.  Everything seemed to be working, except
that at 100% completion the progress bar spanned only about 75% of the
canvas width.  Eventually I tracked the problem down to the canvas bar
'width' property as read using w=cnvProgess['width'].  It turned out
the value returned was the original width of the canvas bar, and not
the screen width after the canvas had been gridded using 'sticky=W+E'.

Once I realised this it was not a show stopper, as I replaced the grid
sticky option with a specific width instruction.  But this is a bit
less flexible than my original method.  Is there any Tkinter command
which will return the actual dimensions of a widget which has had the
grid sticky option applied?

Peter

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


Is there anyway to selectively inherit/import a class/module?

2012-01-03 Thread Peter
I have a program that talks to a device via a serial interface.
Structurally it looks like this:

Program A -> module B -> Serial

I want to add a protocol layer around the serial port without
modifying any of the modules above and I want to be able to use BOTH
cases of the program whenever convenient, so at first it seemed like a
simple case of sub-classing the Serial class and then (this is the
problem) somehow use either the original serial class definition when
I wanted the original program functionality or the new class when I
wanted the extra layer present.

Module B has

import serial

so my first thought was to put the new module in the current directory
and call it "serial.py". This would allow me to run the program with
the new Serial class and when I didn't want that extra layer, all I
had to do was rename the module to something else and let Module B
pick up serial from the site-package area. But (obviously) this
doesn't work because the new class's first few statements are:

import serial

Class Serial(serial.Serial):

So when Module B does the import (and gets the new class definition),
I get an error message (as the new definition is loaded):

AttributeError: 'module' object has no attribute 'Serial' on the Class
declaration statement.

Is there anyway to have Module B use the new class without modifying
the content of Module B?

The only other alternative I can think of is to create a copy of the
original program, rename the new class file and have two complete
copies of the program but that is not ideal :-)

Thanks
Peter

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


Re: Book authoring

2012-01-03 Thread Peter
On Jan 4, 9:34 am, wesley chun  wrote:
> fwiw, i've given a related talk a couple of times on this subject, the
> most recent of which was at EuroPython this 
> summer:http://ep2011.europython.eu/conference/talks/writing-books-using-pyth...
>
> the content includes a couple of the tools mentioned in this thread as
> well as some author case studies. slide deck's available there too.
>
> cheers,
> --wesley
>
> On Dec 9 2011, 7:43 am, Nick Dokos  wrote:
>
>
>
>
>
>
>
>
>
> > Grant Edwards  wrote:
> > > On 2011-12-09, Miki Tebeka  wrote:
> > > > Greetings,
>
> > > > Any recommendations for abook authoringsystem that supports the 
> > > > following:
> > > > 1. Code examples (with syntax highlighting and line numbers)
> > > > 2. Output HTML, PDF, ePub ...
> > > > 3. Automatic TOC and index
> > > > 4. Search (in HTML) - this is a "nice to have"
>
> > >http://en.wikipedia.org/wiki/Lightweight_markup_language
>
> > > I've used asciidoc extensively and reStructuredText a little. Asciidoc
> > > will produce all the formats you mentioned (though I've only refularly
> > > used HTML and PDF). reStructuredText is what's used for Python docs
> > > isn't it?
>
> > > > Can I somehow use Sphinx?
>
> > > Don't know what Sphinx is.
>
> > I think Sphinx is used for the python docs: it sits atop rST and does
> > all the transformations/processing to produce the desired output
> > (http://sphinx.pocoo.org)
>
> > > And there's always the old stand-by LaTeX, but it's a bit more
> > > heavyweight with more of a learning curve.  OTOH, it does produce
> > > text-book quality output.
>
> > There is also orgmode, which has been used for a few books
> > (http://orgmode.org). I know it does HTML and PDF (the latter through
> > latex), but I'm not sure about ePub: ISTR somebody actually did ePub for
> > his book but I don't remember details. The indexing is manual:
> > add #+index: foo entries as required.  But in general, imo, automatic
> > indexing for books sucks raw eggs (it works much better for highly
> > regular source code like the python source base).
>
> > Nick
>
> --
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python", Prentice Hall, (c)2007,2001
> "Python Fundamentals", Prentice Hall, (c)2009
>    http://corepython.com
>
> wesley.chun : wescpy-gmail.com : @wescpy/+wescpy
> python training and technical consulting
> cyberweb.consulting : silicon valley, cahttp://cyberwebconsulting.com

My apologies, but I just read the intro - no time to watch the video,
so I am probably missing the point of your post :-)

TeX/LaTeX is open source and does an excellent job - plus you can use
your favourite editor to enter the text (I have never been able to
understand why wordprocessors have never been extended beyond the
range of simple text entry functions - most editors offer so many aids
to text entry so you would think some WPs would have taken the hint
and put some more features in!).

So does this just re-invent the wheel (so to speak)?

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


Re: Is there anyway to selectively inherit/import a class/module?

2012-01-03 Thread Peter
On Jan 4, 12:06 pm, Steven D'Aprano  wrote:
> On Tue, 03 Jan 2012 14:21:36 -0800, Peter wrote:
> > I have a program that talks to a device via a serial interface.
> > Structurally it looks like this:
>
> > Program A -> module B -> Serial
>
> I don't understand what this means. Program A points to module B, which
> points to ... what is Serial? Where is it? Is it a class inside the
> module, or another module?
>
> > I want to add a protocol layer around the serial port without modifying
> > any of the modules above and I want to be able to use BOTH cases of the
> > program whenever convenient,
>
> Where are you using them from? Program A, or another program?
>
> I don't see any way to add the extra functionality to Program A without
> modifying Program A. But if you're okay with that, here's a way to
> conditionally define a class to use:
>
> # inside Program A
> import moduleB
>
> if condition:
>     Serial = moduleB.Serial  # I assume moduleB has a Serial class
> else:
>     class Serial(moduleB.Serial):  # subclass
>         def mymethod(self):
>             pass
>
> connection = Serial(...)
>
> > so at first it seemed like a simple case of
> > sub-classing the Serial class and then (this is the problem) somehow use
> > either the original serial class definition when I wanted the original
> > program functionality or the new class when I wanted the extra layer
> > present.
>
> No problem. Here's another way to do it:
>
> from moduleB import Serial as SimpleSerial
> class ComplexSerial(SimpleSerial):
>     ...
>
> And now you can use both at the same time.
>
> --
> Steven

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


can a subclass method determine if called by superclass?

2012-01-04 Thread Peter
Situation: I am subclassing a class which has methods that call other
class methods (and without reading the code of the superclass I am
discovering these by trial and error as I build the subclass - this is
probably why I may have approached the problem from the wrong
viewpoint :-)).

Problem: when overriding one of these "indirectly called" superclass
methods I would like to take differing actions (in the subclass
instance) depending on whether it is the superclass or the subclass
instance performing the call.

Question: Is there any way to determine in a method whether it is
being called by the superclass or by a method of the subclass
instance?

Now I suspect that what I am doing is actually very muddy thinking :-)
and I don't want to attempt to explain why I am approaching the design
this way as an explanation would require too much work - I will
consider an alternative inheritance approach while waiting an answer,
but the answer to the question interested me (even if I do a redesign
and come up with a more "elegant" approach to the problem).

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


Re: can a subclass method determine if called by superclass?

2012-01-04 Thread Peter
On Jan 5, 10:09 am, Ian Kelly  wrote:

>
> Well, you could get the previous stack level using
> traceback.extract_stack() and check the filename.  But it sounds like
> what you actually have are two different methods -- one that is used
> by the superclass, and one that only the subclass knows about and
> uses.  Why not implement it as such?

Thanks Ian - that is one possibility.

I am trying to create a subclass with slightly different functionality
and use it with an existing code base i.e. there is already one or
more modules that instantiate the current superclass and I want to
just drop in this new class to replace it with no ripples up the line
(so to speak). The new class implements some interface changes that
can safely be hidden from the rest of the application.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help me get excited about python 3

2012-01-06 Thread peter
I'm sure Python 3 is wonderful, but I make heavy use of the Python
Imaging Library, which as I understand it has not been adapted to
Python 3.  There may be alternatives, but as I have a large amount of
working code using PIL I am reluctant to drop it just yet.

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


Error in Python documentation

2006-01-21 Thread Peter
I found a minor error in the Python documentation for 2.4 which I
thought I would report. But after a while I gave up. I wonder if this
sort of reporting which is less than a bug could be made easier? The
error was that the index entry to 'print statement' sent me to
http://www.python.org/doc/2.4.2/lib/types.html#l2h-90. From the point
of view of making Python accessible this sort of typo should be easily
reportable.

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


Re: Error in Python documentation

2006-01-21 Thread Peter
>From http://www.python.org/doc/2.4.2/ go to the Library reference
http://www.python.org/doc/2.4.2/lib/lib.html from there to the index
(i) at http://www.python.org/doc/2.4.2/lib/genindex.html. In the index
select 'p' and  click to reach
http://www.python.org/doc/2.4.2/lib/types.html#l2h-90 . At the foot of
this page is a link: "See About this document... for information on
suggesting changes." which if you follow takes you to
http://www.python.org/doc/2.4.2/lib/about.html where there is:

 If you find specific errors in this document, either in the content or
the presentation, please report the bug at the Python Bug Tracker at
SourceForge.

So you need to add a bug to the Python bug tracker -- at least so it
seems. 

Peter

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


Re: How to use pdb?

2006-07-21 Thread peter
I haven't tried to use pdb myself, but this looks fairly helpful ...

http://www.ferg.org/papers/debugging_in_python.html

good luck

Peter

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


find, replace and save string in ascii file

2006-08-23 Thread peter
Hello all,

I'm looking for an advice.

Example (one block in ascii file):
$
NAME='ALFA'
CODE='x'
$

There are many similar blocks in the file with different NAMEs and
different CODEs. What I'm looking for is a script that searchs through
whole file and finds all strings with name ALFA and based on what CODE
is after each ALFA (can be x, y or z) the ALFA name is replaced by
BETAx,BETAy or BETAz and so changed file saves.

What I did is that I can find all strings which I need, next I change
these strings based on CODE, but what I can't is to replace old string
with new one, on the same position in the file. It always writes new
string at the end of the file. Here is my code

Thanks in advance for any kind of help. Regards, Boris


import shutil

NamFile="test2.nam"
BackupNamFile = 1
if BackupNamFile == 1:
shutil.copyfile(NamFile,NamFile.replace(".nam",".nam.bak"))
LineNum=1
LineNumQuantity=0
ArrayCount=0
LineNumArray=[]
ReqArray=[]
ReqName=""
NamFileOpen=file(NamFile,"r+")
for line in NamFileOpen:
LineTextFound1 = line.find("bk")
LineTextFound2 = line.find("_results")
if LineTextFound1 != -1 and LineTextFound2 != -1:
ReqName=line.split("'")[1]
print "Line: \t\t\t"+ str(LineNum)
print "Request Name: \t\t"+ ReqName
LineNumQuantity = LineNum + 2
ReqArray=[LineNum-2,ReqName]
if LineNum == LineNumQuantity:
QuantityName=line.split("'")[1]
print "Quantity Type: \t\t"+QuantityName
if QuantityName == "dx":
Suffix = "_disp"
elif QuantityName == "vx":
Suffix = "_velo"
elif QuantityName == "fx":
Suffix = "_force"
else:
Suffix = "_results"
print "Suffix: \t\t"+Suffix
NewReqName=ReqName.replace("_results",Suffix,1)
ReqArray.append(NewReqName)
LineNumArray.insert(ArrayCount,ReqArray)
ArrayCount+=1
print "New Request Name: \t"+NewReqName
print "---"
LineNum = LineNum+1
print LineNumArray
print len(LineNumArray)
NamFileOpen.close()

NamFileOpen2=file(NamFile,"r+")
LineNum=1
for i in LineNumArray:
print i
for line in NamFileOpen2:
print line
print LineNum
print i[1]
if i[0]== LineNum:
print i[0]
print LineNum
print line
Temp=line.replace(line.split("'")[1],i[2],1)
print Temp
NamFileOpen2.write(Temp) 
LineNum=LineNum+1 
NamFileOpen2.close()

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


Re: find, replace and save string in ascii file

2006-08-23 Thread peter
Thank you for your advice.

I'm not so good in python yet, so could you be so kind and write me a
piece of code for the part

 If you want the output to be written to same file just 'move' this
 temperory file to the input file once you are done.

Because that's what I don't know how to do it. How to replace a string
in the middle of the file and than save this file.

Thanks a lot.


Amit Khemka wrote:
> On 23 Aug 2006 05:48:37 -0700, peter <[EMAIL PROTECTED]> wrote:
> > Hello all,
> >
> > I'm looking for an advice.
> >
> > Example (one block in ascii file):
> > $
> > NAME='ALFA'
> > CODE='x'
> > $
> >
> > There are many similar blocks in the file with different NAMEs and
> > different CODEs. What I'm looking for is a script that searchs through
> > whole file and finds all strings with name ALFA and based on what CODE
> > is after each ALFA (can be x, y or z) the ALFA name is replaced by
> > BETAx,BETAy or BETAz and so changed file saves.
> >
> > What I did is that I can find all strings which I need, next I change
> > these strings based on CODE, but what I can't is to replace old string
> > with new one, on the same position in the file. It always writes new
> > string at the end of the file. Here is my code
>
> A simpler way can be:
>
> 1. Read a 'block' from the input file, ( you can simply read a line
> starting with 'NAME' and keep on reading till you find a line with
> starting 'CODE')
> 2. Once you have read a 'block', make whatever you want changes to the
> NAME and then write the 'block' to a temperory file.
>
> If you want the output to be written to same file just 'move' this
> temperory file to the input file once you are done.
>
> Note: if there is other stuff in the input file, apart from such
> 'blocks' that you want to preserve, a small modification in step 1
> would take care of it.
>
> hth,
> amit.
>
> --
> 
> Amit Khemka -- onyomo.com
> Home Page: www.cse.iitd.ernet.in/~csd00377
> Endless the world's turn, endless the sun's Spinning, Endless the quest;
> I turn again, back to my own beginning, And here, find rest.

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


Tkinter check box behaviour - Windows / Linux discrepancy

2006-11-09 Thread peter
I've come across a weird difference between the behaviour of the
Tkinter checkbox in Windows and Linux.  The issue became apparent in
some code I wrote to display an image in a fixed size canvas widget. If
a checkbox was set then the image should be shrunk as necessary to fit
the canvas while if cleared it should appear full size with scrollbars
if necessary.

The code worked fine under Linux (where it was developed).  But under
Windows, the first click in the checkbox did nothing, then subsequent
clicks adjusted the size according to the PREVIOUS, not the current,
checkbox state.

I've isolated the problem in the code below, which shows a single
checkbox and a label to describe its state. It works ok under Linux,
but in Windows it is always one click behind.

Any ideas?  I am using
   Linux: Fedora Core 3, Python 2.3.4
   Windows: Windows NT, Python 2.3.4

Peter


import Tkinter as tk



class App:

def __init__(self,frmMain):

"""
Demonstrate difference in Windows / Linux handling of check box

Text in lblTest should track check box state
"""

# Set up form

self.intTest=tk.IntVar()

self.chkTest=tk.Checkbutton(frmMain,text='Click
me!',variable=self.intTest)

self.chkTest.grid(row=0,column=0,padx=5,pady=5,sticky=tk.W)

self.chkTest.bind('',self.chkTest_click)



self.lblTest=tk.Label(frmMain,text='Dummy')

self.lblTest.grid(row=1,column=0,padx=5,pady=5,sticky=tk.W)


self.chkTest_click() # so as to initialise text

def chkTest_click(self,event=None):
# read check box state and display appropriate text
if self.intTest.get()==0:
self.lblTest.config(text='Check box cleared')
else:
self.lblTest.config(text='Check box set')




if __name__=='__main__':

frmMain=tk.Tk()

app=App(frmMain)

frmMain.mainloop()

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


Re: Tkinter check box behaviour - Windows / Linux discrepancy

2006-11-10 Thread peter
Thank you for those suggestions

I've tried it on Windows and it seems fine (with the minor change to
command=self.chkTest_click).  I'm currently at work, with no access to
Linux, so can't test it there until this evening.  

Muchas gracias!

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


Re: Tkinter check box behaviour - Windows / Linux discrepancy

2006-11-10 Thread peter
Thank you for those suggestions

I've tried it on Windows and it seems fine (with the minor change to
command=self.chkTest_click).  I'm currently at work, with no access to
Linux, so can't test it there until this evening.  

Muchas gracias!

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


Re: PIL problem after installation

2006-06-12 Thread peter
I had similar problems a couple of months back when I was teaching
myself Tkinter and PIL.  I wrote up my experiences here:-

http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm


If you look at the section on Images you will see how I eventually
solved it (with bucket loads of help from this forum)

Good luck

Peter

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


Re: Detecting key presses

2006-06-19 Thread peter
Not a stupid question at all - its something I was looking for, and was
(and still am) surprised not to find a cross platform implementation.
It must be possible - for a short while I dabbled with yabasic and
there the same source code would recognise a keypress in both Windows
and Linux.

My solution was:-

# Await key and return code - dos only
def _keycode_msvcrt(self):
#Loop till key pressed
while 1:
if msvcrt.kbhit():
k=ord(msvcrt.getch())
if k==0 or k==224:#Special keys
   k=1000+ord(msvcrt.getch()) #return 1000+ 2nd code
pass
break
pass
pass
return k

# Await key and return code - linux only
def _keycode_linux2(self):
# Loop till key pressed
# Set up keycode list
a=[0,0,0,0,0,0]

# Press a key and populate list
try:
os.system('stty -icanon')
os.system('stty -echo')
a[0]=ord(sys.stdin.read(1))
if a[0]==27:
a[1]=ord(sys.stdin.read(1))
if a[1]==91:
a[2]=ord(sys.stdin.read(1))
if (a[2]>=49 and a[2]<=54) or a[2]==91:
a[3]=ord(sys.stdin.read(1))
if a[3]>=48 and a[3]<=57:
a[4]=ord(sys.stdin.read(1))
finally:
os.system('stty echo')
os.system('stty icanon')

# Decode keypress
if   a==[ 10,  0,  0,   0,   0, 0]: k=  13   # Enter
elif a==[ 27, 27,  0,   0,   0, 0]: k=  27   # Esc (double
press)
elif a==[ 27, 91, 91,  65,   0, 0]: k=1059   # F1
elif a==[ 27, 91, 91,  66,   0, 0]: k=1060   # F2
elif a==[ 27, 91, 91,  67,   0, 0]: k=1061   # F3
elif a==[ 27, 91, 91,  68,   0, 0]: k=1062   # F4
elif a==[ 27, 91, 91,  69,   0, 0]: k=1063   # F5
elif a==[ 27, 91, 49,  55, 126, 0]: k=1064   # F6
elif a==[ 27, 91, 49,  56, 126, 0]: k=1065   # F7
elif a==[ 27, 91, 49,  57, 126, 0]: k=1066   # F8
elif a==[ 27, 91, 50,  48, 126, 0]: k=1067   # F9
elif a==[ 27, 91, 50,  49, 126, 0]: k=1068   # F10
elif a==[ 27, 91, 50,  51, 126, 0]: k=1133   # F11
elif a==[ 27, 91, 50,  52, 126, 0]: k=1134   # F12
elif a==[ 27, 91, 50, 126,   0, 0]: k=1082   # Ins
elif a==[ 27, 91, 51, 126,   0, 0]: k=1083   # Del
elif a==[ 27, 91, 49, 126,   0, 0]: k=1071   # Home
elif a==[ 27, 91, 52, 126,   0, 0]: k=1079   # End
elif a==[ 27, 91, 53, 126,   0, 0]: k=1073   # Pg Up
elif a==[ 27, 91, 54, 126,   0, 0]: k=1081   # Pg Dn
elif a==[ 27, 91, 65,   0,   0, 0]: k=1072   # Up
elif a==[ 27, 91, 66,   0,   0, 0]: k=1080   # Down
elif a==[ 27, 91, 68,   0,   0, 0]: k=1075   # Left
elif a==[ 27, 91, 67,   0,   0, 0]: k=1077   # Right
elif a==[127,  0,  0,   0,   0, 0]: k=   8   # Backspace
else:   k=a[0]   # Ascii code

# Done
return k


# Return key code
def key(self,case='NONE'):

# Get OS name and call platform specific function
a=sys.platform
if a=='linux2':   #Linux (works on Fedora
Core 1 and 3)
k=self._keycode_linux2()
elif a=='win32':  #windows
k=self._keycode_msvcrt()
else: #unknown
k=ord(raw_input())

# Adjust case
if case=='UPPER':
 if k>=97 and k<=122:
  k=k-32
if case=='LOWER':
 if k>=65 and k<=90:
  k=k+32

# Done
return k

A bit clumsy, I know (for example it needs a a double press to
recognise the escape key), and I'm not sure I understand why it works,
but for me it was a passable solution.

Peter

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


tkMessagebox.askyesno always returns False

2006-06-21 Thread peter
I have a weird problem in some code I am writing.  The user selects a
number of files from a list and then can select an option which will
rename the selected files.  Before the process starts, a yes/no dialog
box pops up just to confirm.

Most of the time this works fine, but occasionally it seem the dialog
box gets into a state where it always returns False, irrespective of
the button clicked.

I must be doing something wrong, but I just can't see it!  Any
suggestions?



import tkMessageBox as mb
 :
 :
if action=='Rename':
yn=mb.askyesno(file_list[0],'Ok to rename %d selected
file(s)' % file_count)
print 'Response: ',yn # Debug only
if not yn: exit_flag=1



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


Re: tkMessagebox.askyesno always returns False

2006-06-22 Thread peter
It's a moderately large application, and so impractical to post it all.
 I'll have a go at isolating circumstances where this fault occurs then
post the preceeding code - but not before this evening (London time)
when I might have some free time. 
Peter

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


Re: tkMessagebox.askyesno always returns False

2006-06-22 Thread peter

I've managed to narrow down the circimstances in which the error
occurs.

The application is a file manager (not terribly original,I know, but my
main purpose is to gain experience in using Tkinter).  It displays the
contents of a directory in a list box, and then applies the function
(in this case rename) to the selected items.  There is also a secondary
list, named tag_list, which can be loaded from disc and used to
preselect files.  If I call the function filter_taglist once, it
behaves itself but after I load a differenct tag list and repeat, then
the confirm dialog always returns False and the action fails.

I'm baffled

Code snippets below show
 1.  Loading the tag file from disc
 2.  Matching the tag file to the main file list
 3.  Renaming all selected files

(comments starting ## have been added in this post)



# Load from file
def load_taglist(self,ask_file_name=1):

#if ask_file_name  get tagfile name
if ask_file_name:
a=fd.askopenfilename(title='Tag
File',initialdir=os.path.split(self.tagfile)[0],filetypes=[('Tagfiles','*.tag'),('All
files','*')])
if a=='':
return
self.tagfile=a
## entTag is an entry bix which shows the name of the current
tag file
self.entTag.delete(0,tk.END)
self.entTag.insert(0,os.path.split(self.tagfile)[1])

# read file
self.taglist=[]
try:
fp=file(self.tagfile,'r')
while 1:
a=pstring(fp.readline())
if a.text=='': break
a.stripcrlf()
self.taglist.append(a.text)
fp.close()
except:
mb.showerror(self.tagfile,'Error reading from tag file')
self.show_taglist()




## This function reads every file in the list box and checks it
against the tag list
def filter_taglist(self):
for i in range(self.lstFiles.size()):
f=self.lstFiles.get(i)
if f in self.taglist:
self.lstFiles.select_set(i)
self.lstFiles.see(i)






## This function applies a user specified function to each selected
file
def file_control(self,action):

## set up list of files - element 0 is the path and elements 1
up are the files
## get_listbox_contents(1) is a function which returns a list
of
## listbox selected contents (instead of just their position
number)

file_list=[self.file_path,]+widget(self.lstFiles).get_listbox_contents(1)
exit_flag=0
file_count=len(file_list)-1
if file_count==0:
mb.showwarning(self.title,action+': No files selected')
return

# Initial conditions. If the user cancels, or the conditions
are insufficient,
# set an escape flag

if action=='Rename':
i=mb.askyesno(file_list[0],'Ok to rename %d selected
file(s)' % file_count)
if i==0: exit_flag=1

## etc


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


Debugging python with c++ extensions under windows with eclipse CDT

2005-05-12 Thread peter
Hello all,

I would like to debug my python libraries, written in c++, with GDB
(gnu debugger)
I'm using the mingw compiler in a windows environment.  As development
environment I use eclipse with the CDT plugin.  This plugin also has a
nice GUI frontend for the GDB.

I've already tried several setups, no setup seemed to work.

Therefore my first question simply is: has anybody already succeeded in
using the GDB used by eclipse CDT to debug a c++ extension?
Is this actually the best way to debug DLLs in windows? Is visual
studio better suited for the job?  Is there another option I am not
aware of?

thx a lot for reading so far

Peter


In the following section I explain in detail what I've already tried.
It can easily be skipped.

Ok, an overview of the things I've already done:
first, to use mingw with the python distribution, I've first followed
http://sebsauvage.net/python/mingw.html in order to get an adjusted
libpython23.a  Otherwise you cannot use the mingw compiler with python
under windows

In order to debug my code, I've found in this newsgroup the topic:
   "Debugging python with C++ extensions"
and similar I've found
http://ruby.wag.caltech.edu/Tutorials/double-debugger.html

I've tried somewhat similar in my eclipse CDT environment:
I start a python script, which pauses at a point I've inserted:
>>>a = raw_input("")
Now I can start the GDB and attach it to this running python process...

In eclipse this is "right mouse click" > debug > debug > "c/c++ attach
to local application"
I create a new configuration of this type, fill in the correct DLL.
(making sure my binary parser was correct, this is usually the problem
if you can't find any binaries)

all this did not same to work...

I get an error" Cannot access memory at address 0x68f52bcc
Cannot access memory at address 0x68f52bcc"
and I no longer understand anything which is going on in the the
debugger.

So again the basic question is: has anybody already succeeded in using
the GDB for debugging python c++ libraries in windows?
Does this also work when you use the eclipse environment?

once again, kind regards

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


Re: reference counting and file objects

2005-05-24 Thread Peter

Martin v. Löwis wrote:
> Paul Rubin wrote:
> >>Consider the function above.  Do I need the fp.close(), or will the
> >>file be closed automatically when fp goes out of scope and its
> >>reference count drops to zero?
> >
> > In CPython, fp gets closed when it leaves scope.
>
> One issue is that when the function terminates through an exception,
> the file stays open as long as the traceback is available, which
> exists until the next exception is raised (and thus replaces this
> traceback).
>
> If the function terminates normally (i.e. through return), it is
> as you say.
>
> Regards,
> Martin

Does the idiom:

lines = file("myfile","r").readlines()

have any better guarantee of being closed automatically? 

Peter

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


Re: Python and (n)curses

2007-06-19 Thread peter
I've said it before and I'll say it again.  Why does Python have no
platform neutral commands for simple screen manipulation?  yabasic (a
'hobby' type language  - http://www.yabasic.de/) has commands clear
screen, inkey$ and putscreen$ which perform the basic functions of
clearing the screen, reading a key press and printing a string at an
arbitrary xy position in either Windows or Linux, leaving all the
messy implementation away from the user.  For me, introducing similar
commands in Python would be by far the biggest single improvement that
could be made to the language.

Yes, I know the argument that it's up to me to contribute such a
module.  But I'm afraid my knowledge and skill are way below the
threshold needed for such work.  Which is why I need it as an addition
to the core language!

Peter

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


Re: PIL cutting off letters

2007-06-19 Thread peter
On 16 Jun, 17:20, Pierre Hanser <[EMAIL PROTECTED]> wrote:
> Matt Haggard a écrit :
>
> > I'm using PIL (Python Imaging Library) to generate button images.
> > They consist of a left end image, a middle, repeating image and a
> > right side image anyway, that's not important
>
> > I'm using a TTF font for the text of the button (Verdana.TTF) and it
> > keeps cutting the bottom part of the the g's q's and y's off.
>
> hello
>
> may be the problem is in your code, but it is also possibly
> in PIL which clips caracters at the top and bottom line;
> that's not the typographic names, but these are *font* values,
> not characters ones.
> There are fonts with caracters far higher than these
> conventionnal lines (try Liorah.ttf or any swashed font for
> exemple)!
> I don't remember for sure but may be there is the same problem
> horizontally.
> --
>     Pierre

I've had this problem horizontally, and solved it by the high tech
method of adding a leading and trailing space!!!

Peter

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

Re: DFW Pythoneers Meeting THIS Saturday

2007-06-20 Thread peter
Just a tad arrogant, don't you think, to put a notice of some local
event on an international forum without saying where it is?



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


Re: Python and (n)curses

2007-06-20 Thread peter

> > For me, introducing similar commands in Python would be by far  the biggest 
> > single improvement that could be made to the language.

> If it should be done, it should be done as a compatible subset of
> curses, IMHO. It has such a long history as the standard "GUI toolkit"

But curses doesn't run under Windows - thats the whole point!

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


Re: DFW Pythoneers Meeting THIS Saturday

2007-06-20 Thread peter

> It says right in the subject line! DFW. If you don't know what DFW
> means, then it's probably not your local area.

Precisely


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


Re: DFW Pythoneers Meeting THIS Saturday

2007-06-21 Thread peter
OK.  Not my intention to start a flame war, but as DFW did not mean a
thing to me (other than being my late father in law's initials) I was
a bit peeved about the assumption that everybody would understand it.
I think posts which are essentially local should make this clear to
all in the title.

I hope the meeting goes well.



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


  1   2   3   4   5   6   7   8   9   10   >