Re: [Tutor] Question on joining out of order dictionary elements

2007-01-11 Thread Andrew Robert
I like this solution.

Thanks everyone for all of the suggestions.

On 1/11/07, Andre Engels <[EMAIL PROTECTED]> wrote:
> 2007/1/11, raghu raghu <[EMAIL PROTECTED]>:
>
> > >>> print "\\".join((config["val2"]
> > ,config["val1"],config["val3"]))
> > elem2\elem1\elem3
> >
> > or
> >
> > >>> print "%s\\%s\\%s" %
> (config["val2"],config["val1"],config["val3"])
> > elem2\elem1\elem3
> >
> > but this seems somehow uneligent.
> >
> > Are there a more efficient/compact ways of doing this kind of
> > operation or is this it?
> >
>
> Maybe you like:
> print "\\".join([config[val] for val in ["val2","val1","val3"]])
>
> --
> Andre Engels, [EMAIL PROTECTED]
> ICQ: 6260644  --  Skype: a_engels
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachusetts Financial Services
Phone: 617-954-5882
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question on joining out of order dictionary elements

2007-01-10 Thread Andrew Robert
Hi everyone,

I have a quick quick question joining out of order dictionary values.

For example:

I created an empty

>>> config={}

Added some key/value pairs

>>> config["test1"]="elem1"
>>> config["test2"]="elem2"
>>> config["test3"]="elem3"

  etc
>>>

Dumped the values and joined them at the same time.

>>> print "\\".join(config.values())
elem1\elem3\elem2

This is fine but it doesn't entirely solve the issue.

Only some of the key/value pairs in the dictionary are needed so a
dump of all values does not work.

Also, the order in which the values are joined is important so walking
through and joining all values does not work either.


The simplest way would be to do something like:

>>> print "\\".join((config["val2"],config["val1"],config["val3"]))
elem2\elem1\elem3

or

>>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?

The key/value pairs in these examples are contrived for purposes of
this discussion but the end goal is to piece together server and
directory path information for use with pysvn.

I have a Perl programmer who is learning Python and he is griping that
this kind of operation is far simpler in Perl.

-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachusetts Financial Services
Phone: 617-954-5882
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Testing the status of NFS mounts

2007-01-04 Thread Andrew Robert

Hi everyone,

We have several NFS mounts that are in use.

Occasionally, the NFS mounts seem to go out to lunch.

The mounts appear active but are no longer functional.

Is there a Python module specific to NFS that I might use to periodically
check its status?

I imagine I could make a script to attempt a write on the share and clean up
after itself but I am hoping for a more elegant solution.

Any insight anyone can provide on this would be greatly  appreciated.

--
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachussetts Financial Services
Phone: 617-954-5882
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pysvn samples

2006-12-15 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi guys,

I am looking to experiment with pysvn and was wondering if anyone knew
of a location for code samples/snippets using it?

I'm reviewing the pysvn programmers guide and tutorial but some live
examples would be great.

If anyone can point me at something, it would be appreciated.

Thanks,
Andy
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)

iD8DBQFFgy7MDvn/4H0LjDwRAmUeAKCRa7qfTx0g3TwPtLL4PxWxlfeZrwCgrEBI
RjJI2onZj/WnLx4FLWoRkIE=
=oJnx
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sending mails from python

2006-10-21 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

How about something like this?

Create a function and then call it with the required optins of server
url, sender address, destination address, subject, and message text?



def send(serverURL=None, sender='', to='', subject='', text=''):
"""
Form and send an e-mail message
"""

import smtplib

headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (sender, to,
subject)
message = headers + text
mailServer = smtplib.SMTP(serverURL) # replace serverURL with site
specific mail server
check_valid=mailer.isAddressValid(to)
if check_valid==1 :
mailServer.sendmail(sender, to, message)
mailServer.quit()
else:
print "\n\nDestination e-mail address %s is invalid.
\n\n\tPlease check and run again" % to



def isAddressValid(addr):
"""
Validate e-mail addresses based on lexical rules set forth in
RFC 822
Ported from Recipe 3.9 in Secure Programming Cookbook for C and
C++ by
John Viega and Matt Messier (O'Reilly 2003)

If the supplied email address is syntactically valid,
isAddressValid()
will return 1; otherwise, it will return 0.
"""
# Mail variables
rfc822_specials = '()<>@,;:\\"[]'

c = 0
while c < len(addr):
if addr[c] == '"' and (not c or addr[c - 1] == '.' or addr[c
- - 1] == '"'):
c = c + 1
while c < len(addr):
if addr[c] == '"': break
if addr[c] == '\\' and addr[c + 1] == ' ':
c = c + 2
continue
if ord(addr[c]) < 32 or ord(addr[c]) >= 127: return 0
c = c + 1
else: return 0
if addr[c] == '@': break
if addr[c] != '.': return 0
c = c + 1
continue
if addr[c] == '@': break
if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return 0
if addr[c] in rfc822_specials: return 0
c = c + 1
if not c or addr[c - 1] == '.': return 0

# Next we validate the domain portion ([EMAIL PROTECTED])
domain = c = c + 1
if domain >= len(addr): return 0
count = 0
while c < len(addr):
if addr[c] == '.':
if c == domain or addr[c - 1] == '.': return 0
count = count + 1
if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return 0
if addr[c] in rfc822_specials: return 0
c = c + 1

return count >= 1

euoar wrote:
> I'm trying to learn how to send e-mails with python. But I always become 
> this error: socket.error: (110, 'Connection timed out'). Is there 
> something bad in the code? Does anyone knows what could be wrong? I'm 
> using python from linux, and have no proxy...
> 
> The code that I use is this (of course, filling with my persona data the 
> " "):
> 
> import smtplib
> 
> smtpserver = 'my smtp server goes here'
> AUTHREQUIRED = 1
> smtpuser = 'my user name'
> smtppass = 'my password'
> 
> RECIPIENTS = ['the recipients']
> SENDER = 'my mail'
> mssg = "una prueba desde python"
> 
> session = smtplib.SMTP(smtpserver)
> if AUTHREQUIRED:
> session.login(smtpuser, smtppass)
> smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
> 
> if smtpresult:
> errstr = ""
> for recip in smtpresult.keys():
> errstr = """Could not delivery mail to: %s
> 
> Server said: %s
> %s
> 
> %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
> raise smtplib.SMTPException, errstr
> 
> 
> 
> Thank you for your help
> 
> 
> 
>   
>   
>   
> __ 
> LLama Gratis a cualquier PC del Mundo. 
> Llamadas a fijos y móviles desde 1 céntimo por minuto. 
> http://es.voice.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFFOhCLDvn/4H0LjDwRAm9AAJwOkrtF/R4zWQhhCwjlBrBVQ4XpwwCgpGHy
ukZIoIuoAh/hmBZ/r/ZbQmM=
=6weK
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python code to split and reassemble files

2006-10-01 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Never mind.. :)


found it at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/224800

However, if someone has something better, I would be very interested.



Andrew Robert wrote:
> Hi guys,
> 
> Awhile back, I believe I saw a cookbook recipe for splitting and
> reassembling text/binary files.
> 
> Does anyone know where this or something similar can be found?
> 
> I am working on a file transfer mechanism via MQSeries and breaking
> large files to smaller chunks would improve efficiency.
> 
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFFH+i/Dvn/4H0LjDwRAr6dAJ48jTQzjWNPEfB3RLkOk9Z93QOalQCcDubg
Fv7y2wpg/kEgt+f6vZwfkdA=
=4c84
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python code to split and reassemble files

2006-10-01 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi guys,

Awhile back, I believe I saw a cookbook recipe for splitting and
reassembling text/binary files.

Does anyone know where this or something similar can be found?

I am working on a file transfer mechanism via MQSeries and breaking
large files to smaller chunks would improve efficiency.

- --
Thank you,
Andrew Robert
Senior MQ Engineer
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD4DBQFFH+RCDvn/4H0LjDwRAtQQAKCeKSCHnsKa5tXye6/bJHm551hyrgCVEp2K
aScfnRPpxVgjJPyM/zqo3Q==
=6LHh
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with parsing

2006-09-18 Thread Andrew Robert
Bryan Leber wrote:
>
> Hello, I am trying to create a script that reads from the command line
> and puts the sysargv into a list. I have this part done. I have added
> code for testing and one of those testing procedures is to print the
> list out in a text file.  Not all field are required and may not have
> information in them. A sample text file looks like this:
>
>  
>
> PATCH_NUMBER: 
>
> BUG_NUMBER: 4534
>
> FEATURE_AFFECTED: Admin login
>
> OVERVEIW: The icon of the submit has changed
>
>  
>
> Now what I need to accomplish is to search through this list and if
> FEATURE_AFFECTED or OVERVIEW do not have values(i.e. Admin login or
> The icon of the submit changed) then I need to print a message and
> then exit.  Right now I have something like this
>
>  
>
> Size = len(argsList)
>
> If size = 4
>
>For i in argsList
>
>If i[2] == None:
>
>   Print ‘please enter criteria’
>
>   Sys.exit()
>
>Elif i[3] == None:
>
>   Print ‘please enter criteria’
>
>   Sys.exit()
>
>Else:
>
> Sys.exit()
>
>  
>
> Any help would be appreciated. Thanks
>
>  
>
>  
>
> **/Bryan Leber/**
>
> Developer
>
> Fischer International Corporation
>
> www.fischerinternational.com 
>
> [EMAIL PROTECTED]
> 
>
> Cell:(239)963-5267
>
>  
>
> Secure Your Risk. Increase Your Bottom Line. ™
>
>  
>
> 
>
> This mail message may contain confidential and privileged information
> from Fischer International which is protected.  Any unauthorized
> review, use, disclosure or distribution by any means is prohibited. 
> If you are not the intended recipient, please contact the sender by
> reply email and destroy all copies of the original message
>
> 

I recommend that you check out the optparse.module from OptionParser

It does what you are looking for in a concise method.

See http://docs.python.org/lib/module-optparse.html

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple SQL server access...

2006-09-06 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


Chris Hengge wrote:
> I've been doing some searching for ways to access existing SQL server
> databases, but I'm finding so many different ways to do it, is there one
> that anyone recommends for a "new to python" programmer? I've used VB
> and C# for accessing SQL, so maybe something that would feel similiar to
> that to get me started?
>  
> Thanks.
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

For a list of modules that can help, I recommend you look at
http://www.python.org/doc/topics/database/modules/

There are specific modules for DB2, Oracle, Sybase, Postgress, MySQL, etc.
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFE/3LkDvn/4H0LjDwRAoJ/AKCQ2HIpfduCorgJmlQsfACWbKKLCQCglYcm
kE5KDOfwu29boHiRiODqEIc=
=TGXp
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple SQL server access...

2006-09-06 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Chris Hengge wrote:
> I've been doing some searching for ways to access existing SQL server
> databases, but I'm finding so many different ways to do it, is there one
> that anyone recommends for a "new to python" programmer? I've used VB
> and C# for accessing SQL, so maybe something that would feel similiar to
> that to get me started?
>  
> Thanks.
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


How about something like this?

I use it for connecting to Oracle databases.

Information on cx_Oracle and similar can be found at
http://www.python.net/crew/atuining/cx_Oracle/




import cx_Oracle

class db:
def __init__(self, db, uname, passwd):
self.connection =
cx_Oracle.connect(dsn=db,user=uname,password=passwd)

def execute(self, sql):
cursor = self.connection.cursor()
cursor.execute(sql)
return cursor

def close(self):
self.connection.close()
self.connection = None # Prevent reusing a closed connection
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFE/3HBDvn/4H0LjDwRAqPlAKCPFY6uzHHHWQ4ZKrq3BfqQy9QufgCfZs0a
Zj69XcmwAlW4L+HbH56Wxf8=
=yMOb
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] omnicomplete vim python

2006-08-29 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1



Mike Hansen wrote:
>  
> 
>> -Original Message-
>> From: [EMAIL PROTECTED] 
>> [mailto:[EMAIL PROTECTED] On Behalf Of Alan Gauld
>> Sent: Tuesday, August 29, 2006 1:26 AM
>> To: anil maran
>> Cc: tutor@python.org
>> Subject: Re: [Tutor] omnicomplete vim python
>>
> [...]
>> This isn't answering Anil's question but

ditto .. but you may wish to consider the following python add-on for VIM.

http://www.vim.org/scripts/script.php?script_id=790

It includes:

Enhanced version of the original (from vim6.1) python.vim for Python
programming language.

The changes since the original python.vim are:

- - changed strings highlighting;
- - enhanced special symbols highlighting inside strings;
- - enhanced numbers highlighting;
- - added optional highlighting for %-formatting inside strings;
- - added highlighting for some error conditions (wrong symbols in source
file,
  mixing spaces and tabs, wrong number values,
  wrong %-formatting inside strings);
- - added highlighting for magic comments: source code encoding
  and #! (executable) strings;
- - added highlighting for new exceptions and builtins introduced in
python 2.3, 2.4 and 2.5;
- - added highlighting for doctests;
- - added highlighting for new @decorator syntax introduced in Python 2.4a2;
- - added highlighting for trailing-space errors (triggered by new
  option: python_highlight_space_errors);
- - added highlighting for variable name errors;
- - added highlighting for hex number errors;
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFE9GYjDvn/4H0LjDwRAtecAJ4oWEqO5CQN0vLyFOKpRyb7PtRhSACgr9gJ
v4MQqzHAFdk8OJMHulpW9uM=
=fces
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [whitelist] Re: regular expressions question

2006-08-22 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Nimrodx,

In case you haven't found a solution yet, I developed a program to
encode/decode stuff similar to this.

You may want to take a look at it at

 http://home.townisp.com/~arobert/python/file_encoder.py



nimrodx wrote:
> Hi Alan,
> 
> I found a pretty complicated way to do it (Alan's way is way more elegant).
> In case someone is searching the archive, maybe they will find something 
> in it that is useful.
> It uses the regular experessions module.
> 
> import re
> 
> def dehexlify_websites(fle):
># get binary data
>inpt = open(fle,'rb')
>dat = inpt.read()
>inpt.close()
>#strip out the hex "0"'s
>pattern = r"\x00"
>res = re.sub(pattern, "", dat)
>#-
>#it seemed easier to do it in two passes
>#create the pattern regular expression for the stuff we want to keep
>web = re.compile(
> r"(?P[/a-zA-Z0-9\.\-:\_%\?&=]+)"
> )
>#grab them all and put them in temp variable
>res = re.findall(web,res)
>tmp = ""
>#oops need some new lines at the end of each one to mark end of
> #web address,
>#and need it all as one string
>for i in res:
>tmp = tmp + i+'\n'
>#compile reg expr for everything between :// and the newline
>web2 = re.compile(r":/(?P[^\n]+)")
>#find the websites
>#make them into an object we can pass
>res2 = re.findall(web2,tmp)
>#return 'em
>return res2
> 
> 
> Thanks Alan,
> 
> Matt
> 
> 
> Alan Gauld wrote:
>>> if you look carefully at the string below, you see
>>> that in amongst the "\x" stuff you have the text I want:
>>> z tfile://home/alpha
>> OK, those characters are obviously string data and it looks
>> like its using 16 bit characters, so yes some kind of
>> unicode string. In between and at the end ;lies the binary
>> data in whatever format it is.
>>
> Here is the first section of the file:
> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l'
>  
>
>>
>>> In a hex editor it turns out to be readable and sensible url's with 
>>> spaces between each digit, and a bit of crud at the end of url's, 
>>> just as above.
>> Here's a fairly drastic approach:
>>
> s = 
> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01 
>
>> \xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x
>>  
>>
>> 00l'
> ''.join([c for c in s if c.isalnum() or c in '/: '])
>> 'ztfile:/home/al'
>> But it gets close...
>>
>> Alan g.
>>
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFE6ySXDvn/4H0LjDwRApntAJ0Wd0ecE/KFUSbbKQSRmrV72yyvfwCeOwAQ
Gjg5IK0WG0YT6keGlDw0q94=
=7QB2
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using python to create and save a Ms Word file

2006-07-21 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,


I wasn't entirely satisfied with the Ms Word solution because it
requires the program run on Windows and have Office installed.

As an alternate solution, I created the program listed below to read a
file and create a RTF file format document from it.

The program is not platform dependent but it does require installation
of the PyRTF module.

I hope someone finds this useful/interesting.


#!C:\Python24\python
#
# program: rtfmaker.py
# Author:  Andrew Robert
#
# Function: Take a supplied file and dump its contents to an RTF file
#   This code is platform independant.
#
# Ver   Date   ProgrammerModification
# 1.0   07/21/06   AAR   Initial Creation
# 1.1added argument and source/target
file testing

import sys, time, string, stat, os
from PyRTF import *
from optparse import OptionParser

def MakeFile(lines):
"""
Create the RTF file
"""

doc = Document()
ss  = doc.StyleSheet
section = Section()
doc.Sections.append( section )

# Append lines from source file
for line in lines:
section.append( line )

return doc

def OpenFile( name ):
return file( '%s' % name, 'w' )

def file_test(file):
"""
Tests user supplied file to see if it exists and contains data.
If the input file does not exist or is empty, return a warning code
"""
if (0 == os.path.isfile(file) or (0 == os.stat(file)[stat.ST_SIZE])):
return 1
else:
return 0

def run_tests(input, output):
"""
Test source file to ensure it exists and contains data
"""
if file_test(input) == 1 :
print "\nError: Source file not found or is empty."
parser.print_help()
sys.exit(1)

# Test target file to prevent accidental clobbering
if file_test(output) == 0 :
print "\nError: Target file already exists."
parser.print_help()
sys.exit(1)



def test_options(infile, outfile):
"""
Verify that required values are specified on commmand line
and that specified port is within range
"""

if not infile :
print "\nError: No input file specified"
parser.print_help()
sys.exit(1)

if not outfile :
print "\nError: No input file specified"
parser.print_help()
sys.exit(1)


if __name__ == '__main__' :

parser=OptionParser()
parser.add_option("-i", "--input" , dest="infile",
  help="Input FILE" , metavar="FILE")
parser.add_option("-o", "--output", dest="outfile",
  help="Output file", metavar="FILE")

(options, args) = parser.parse_args()

test_options( options.infile , options.outfile )
run_tests(options.infile , options.outfile)

DR = Renderer()
lines = open(options.infile,"r").readlines()
rtffile = MakeFile(lines)

# Write the new RTF file to disk
DR.Write( rtffile, OpenFile( options.outfile ) )
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEwO9uDvn/4H0LjDwRAlHSAJ9KIzPYT2YHdK8MptBS8JSIdt8dZACgsfKi
nZQ3Bs71jsbFplmwbnVEIgI=
=ZPSo
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using python to create and save a Ms Word file

2006-07-21 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-

Hash: SHA1



Thanks for your help on this.

Here is the completed code in case anyone is interested.

#! C:\Python24\python 
#
# program: mswword.py
# Author:  Andrew Robert
# 
# Ver   Date   ProgrammerModification
# 1.0   07/20/06   AAR   Initial Creation
# 1.1   07/21/06   AAR   added doc save/quit items to class
# 1.2added argument and source/target file 
testing 

import sys, time, string, win32com.client, stat, os

class CWordAutomate:
"""Encapsulates a winword com connection"""
def __init__( self ):
"""construct: create OLE connection to winword"""
self.m_obWord = win32com.client.Dispatch( "Word.Application" )
self.m_obDoc  = self.m_obWord.Documents.Add( ) # create new doc
self.m_obWord.Visible = 1
self.m_Sel= self.m_obWord.Selection # get a selection

def WriteLine( self, sTxt, sFont, lSize, bBold=0 ):
"""Write a line to winword"""
self.m_Sel.Font.Name = sFont
self.m_Sel.Font.Bold = bBold
self.m_Sel.Font.Size = lSize
self.m_Sel.TypeText( Text=sTxt + "\n"  )

def Save(self, sFilename):
self.m_obDoc.SaveAs(sFilename)

def Quit(self):
self.m_obWord.Quit()


def file_test(file):
"""
Tests user supplied file to see if it exists and contains data.
If the input file does not exist or is empty, return a warning code
"""

if (0 == os.path.isfile(file) or (0 == os.stat(file)[stat.ST_SIZE])):
return 1
else:
return 0


if __name__ == "__main__":

usage = "\n\n\tUsage:  msword.py  {inputfile}  {outputfile}\n"

#
# Test number of arguments passed.
#
if len(sys.argv) != 3:
print "\n\n\tmsword.py error: \n\n\tInsufficient arguments 
passed."
print usage
sys.exit(1)


# Test source file to ensure it exists and contains data
if file_test(sys.argv[1]) == 1 : 
print "\n\n\tmsword.py error: \n\n\tSource file not found or is 
empty."
print usage
sys.exit(1)

# Test target file to prevent accidental clobbering
if file_test(sys.argv[2]) == 0 :
print "\n\n\tmsword.py error: \n\n\tTarget file already exists."
print usage
sys.exit(1)


sFileName  = sys.argv[1]
obFile = file( sFileName, 'r+' )
sContent   = obFile.read()
obFile.close()
lstContent = sContent.splitlines()

# 
# Write contents of source file to user supplied file name
#
obWord = CWordAutomate()

for sLine in lstContent:
obWord.WriteLine( sLine, "Courier New", 10  )

sLastMsg = time.strftime( "document generated on %c", time.localtime()  
)
obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )

obWord.Save(sys.argv[2])
obWord.Quit()



andrew clarke wrote:
> On Thu, Jul 20, 2006 at 01:25:26PM -0400, Andrew Robert wrote:
> 
>> I have a text file being broadcast on a web site and I would like to 
>> download it 
>> and save it as an MS Word file.
> 
> ...
> 
>> I found the following code on the web that comes close to what i need.
>>
>> It:
>>
>> - - reads a file passed to it
>> - - opens word file 
>> - - dumps the read contents to the file
>> - - places a time stamp at the end signaling when the conversion occured
>>
>> What is is missing is how to automate saving/closing the file when the 
>> conversion is complete.
>>
>> Would someone be able to help fill in the blanks on this?
> 
> I've never played with Win32 COM before, but your message inspired me to
> learn.  :-)
> 
> A quick Google later, and it seems you need to add the following methods
> to the CWordAutomate class:
> 
> def Save(self, sFilename):
> self.m_obDoc.SaveAs(sFilename)
> 
> def Quit(self):
> self.m_obWord.Quit()
> 
> Then in your code:
> 
>> sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
>> obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )
> 
> Add these:
> 
> obWord.Save("blah.doc")
> obWord.Quit()
> 
> On my system, "blah.doc" was saved as
> 
> C:\Documents and Settings\ozzmosis\My Documents\blah.doc
> 
> So you'll need to specify an absolute pathname if you want it to be
> saved somewhere else.

[Tutor] Using python to create and save a Ms Word file

2006-07-20 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-

Hash: SHA1



Hi Everyone,

I have a text file being broadcast on a web site and I would like to download 
it 
and save it as an MS Word file.

The download from web is relatively painless.

#!C:\Python24\Python
import sys
from urllib import urlopen


if  len(sys.argv) == 1 :
print "\nUsage:   getkwik.py  {output file name} \n"
else:
   open(sys.argv[1],"wb").write( urlopen("http://mydomain/file.txt";).read() )

Trying to get the file to word is a little more troubling.


I found the following code on the web that comes close to what i need.

It:

- - reads a file passed to it
- - opens word file 
- - dumps the read contents to the file
- - places a time stamp at the end signaling when the conversion occured

What is is missing is how to automate saving/closing the file when the 
conversion is complete.

Would someone be able to help fill in the blanks on this?




import sys
import time
import string
import win32com.client

# 
class CWordAutomate:
"""Encapsulates a winword com connection"""
def __init__( self ):
"""construct: create OLE connection to winword"""
self.m_obWord = win32com.client.Dispatch( "Word.Application" )
self.m_obDoc  = self.m_obWord.Documents.Add( ) # create new doc
self.m_obWord.Visible = 1
self.m_Sel= self.m_obWord.Selection # get a selection

def WriteLine( self, sTxt, sFont, lSize, bBold=0 ):
"""Write a line to winword"""
self.m_Sel.Font.Name = sFont
self.m_Sel.Font.Bold = bBold
self.m_Sel.Font.Size = lSize
self.m_Sel.TypeText( Text=sTxt + "\n"  )

# 

# - open a file
sFileName  = sys.argv[1]
obFile = file( sFileName, 'r+' )
sContent   = obFile.read()
obFile.close()
lstContent = sContent.splitlines()

# - display contents in word
obWord = CWordAutomate()
obWord.WriteLine( "Content of the file " + sFileName, "Times New Roman", 18, 1 )
for sLine in lstContent:
obWord.WriteLine( sLine, "Courier New", 10  )
sLastMsg = time.strftime( "document generated on %c", time.localtime()  )
obWord.WriteLine( sLastMsg, "Times New Roman", 14, 0 )

-BEGIN PGP SIGNATURE-

Version: GnuPG v1.2.1 (MingW32)

Comment: GnuPT 2.7.2



iD8DBQFEv7yGDvn/4H0LjDwRAiPPAKCi4LCSuB0qobKavoKqZZ13E7grbwCgriQ8

Bz4uP7IcwipZdfSUUFDi9Hg=

=C1Gx

-END PGP SIGNATURE-

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python module and HP OpenView

2006-07-12 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi everyone,

Does anyone know if there are Python modules available for dealing with
HP OpenView?

I found documentation for connecting to the service navigator and
parsing the data via ElementTree or similar XML parsers.

I was just wondering if there were anything specifically created.

Any insight you might have on this would be greatly appreciated.



- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEtSITDvn/4H0LjDwRAkeJAJ45nfP3OCuvj/o40dhqh2J7yPPCigCZAZb6
rIMNmIoK1RI+tvaqAMkagRc=
=RErH
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to check a files size

2006-06-28 Thread Andrew Robert
Perhaps this?

stat = os.stat(self.file_name)

file_size = stat[6]


Thank you, 
Andrew Robert 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I add my folder to pythonpath?

2006-06-23 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

What you need to do is append your existing path.

for example:

import sys
sys.path.append(r'd:\python_modules')

You can then import any modules that reside in that path as if they
where part of the standard library.


Andy
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEnF+aDvn/4H0LjDwRAl14AKDEfZc0TKEbfhtF+/4h7o56MnCeSACdG6y8
DwLC/UAbZMBHNCQDS/2A5jY=
=HmM2
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question regarding commit/backout of a message using the pymqi module

2006-06-22 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi everyone,

Could someone help explain what I am doing wrong in
this code block?

This code block is an excerpt from a larger file that receives
transmitted files via IBM WebSphere MQSeries an drops it to the local
file system.

Transmission of the file works as designed but it has a flaw.

If the file cannot be created for whatever reason, the transmitted
message is lost.

What I am trying to do is ensure that a file transmit is considered
successful only after the created file's checksum matches.

If not, the code should treat it as an error and roll back the message
to MQSeries without a commit.

The basis for this should be around the pymqi.QueueManager class which
is named mq in the block listed below.

On execution, I get the traceback of:

Traceback (most recent call last):
  File "M:\MQ\MQ\Scripts\receiver.py", line 269, in ?
receiver.run()
  File "M:\MQ\MQ\Scripts\receiver.py", line 109, in run
self.connect()
  File "M:\MQ\MQ\Scripts\receiver.py", line 118, in connect
self.qm.begin()
  File "c:\python24\lib\site-packages\pymqi.py", line 738, in begin
raise MQMIError(rv[0], rv[1])
pymqi.MQMIError: MQI Error. Comp: 1, Reason 2121: WARNING:
MQRC_NO_EXTERNAL_PARTICIPANTS



Do you have any idea why this might be occurring?


class Receiver(object):
def __init__(self,qm_name,queue_name):
self.qm_name = qm_name
self.queue_name = queue_name

# Will be set later
self.qm = None
self.message = None

def run(self):
self.connect()
self.get()

def connect(self):
"""
Connect to queue manager
"""
try:
self.qm = mq.QueueManager(options.qmanager.upper() )
self.qm.begin()
except mq.PYIFError, err:
mqevlog.event("error",err)
sys.exit(1)


def get(self):
"""
Get a message from queue.
"""
queue = mq.Queue(self.qm, self.queue_name)
pmo = mq.pmo(Options = CMQC.MQPMO_SYNCPOINT)
md = mq.md()



while True:
try:
var = queue.get(self.message, md, pmo )
except mq.MQMIError,e:
if e.reason != CMQC.MQRC_NO_MSG_AVAILABLE:
mqevlog.event("error",e)
sys.exit(1)
break
else:
buff = StringIO(var)
tree = ElementTree(file=buff)

# Extract required elements and assign to local 
variables
key   = "this should be a well-kept secret"
file_name = tree.find("dest").text
creation_time = tree.find("creation_time").text
contents  = tree.find("contents").text
check = tree.find("checksum").text


#Decode temp file
original = file_encoder.decode(contents)


# Drop file to disk
if  os.path.exists(file_name) is False:
open(file_name,"wb").write(original)
else:
mqevlog.event(sys.argv[0],"error","Output file 
path/name already
exists")
sys.exit(1)

# Get checksum of newly created file
sum=csums.getsum(file_name)

# Compare checksum of created file with value 
transmitted
if 
csums.checksum_compare(sys.argv[0],sum,check,file_name) == True:
queue.commit()
sys.exit(0)
else:
queue.backout()
mqevlog.event("error","CheckSums of
received/transmitted files do not match")
sys.exit(1)



Any help/insight you can provide on this would be greatly appreciated.


- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEmoCtDvn/4H0LjDwRAonCAKCAiWPpO1UcXWMKIP8xPzCtzP6eLACeMWFO
qmHgdq/nI3gJ1v3jquDKnu8=
=Ga33
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Universal error handler

2006-06-20 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

You may also want to try a error handling like this.

It is platform clean and uses the system standard logging routines.


import os, logging, logging.handlers


def eventlogger(level,message):
"""
Sent trapped events to NT application event logger
"""

if os.name == "nt":

logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
ntl = logging.handlers.NTEventLogHandler("Program Event Logger 
Message")
logger.addHandler(ntl)

try:
method = getattr(logger,level)
message = "%s message: %s" % 
(level.capitalize(),message)
method(message)
sys.exit(0)
except AttributeError:
method = logger.critical
message = "Uncoded event level"
method(message)
sys.exit(1)

else :
import syslog, time
timestamp = time.asctime(time.localtime(time.time()))
logmsg = "Event Logger -   %s  - %s :: $s " % (timestamp,
level.capitalize(),message)
syslogg.syslog(logmsg)




You then call it as a function from wherever an error gets raised.

   msg="OH NO - blue screen of death"
   eventlogger("error",msg)

   msg="OH NO - system slow - scary but you will live"
   eventlogger("warning",msg)

   msg="Shh - don't tell anyone but it worked"
   eventlogger("info",msg)
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEmEB2Dvn/4H0LjDwRAhlmAKCzch2JVynMsNcCY9Cnu8crMqN5fQCfQJWu
ZT8frQiRZXKJZMLeGnyeFbM=
=zCBc
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If then else question

2006-06-14 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Excellent.. much better than testing each value independently.

Thank you.



Mike Hansen wrote:
>  
> 
>> -Original Message-
>> From: [EMAIL PROTECTED] 
>> [mailto:[EMAIL PROTECTED] On Behalf Of Andrew Robert
>> Sent: Wednesday, June 14, 2006 12:41 PM
>> To: Python Tutor
>> Subject: [Tutor] If then else question
>>
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> Hi Everyone,
>>
>> In the middle of an if then else, I have the following line
>>
>>  elif ch_val == '040' or ch_val == '011' or ch_val == '012':
>>
>>
>> The line works but it is a little ungainly.
>>
>> Anyone have a better way of accomplishing the same thing?
>>
>>
>> - --
>> Thank you,
>> Andrew Robert
>>
> 
> Maybe...
> 
> elif ch_val in ['040', '011', '012']:
> 
> Mike
> http://users.adelphia.net/~mahansen/programming/ 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEkFs3Dvn/4H0LjDwRApi/AJ4lyyJOoHWt1NzMBPF2gF7qQsA9WgCguYcd
MmjCVxL4giSzpdA1pRKgnHc=
=y80v
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] If then else question

2006-06-14 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,

In the middle of an if then else, I have the following line

elif ch_val == '040' or ch_val == '011' or ch_val == '012':


The line works but it is a little ungainly.

Anyone have a better way of accomplishing the same thing?


- --
Thank you,
Andrew Robert

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEkFgfDvn/4H0LjDwRAophAKCZbJaMWBr2G8dLjHO3VtOA98/+1gCbBsys
4B/Q6g9m+3DW+PzcnCpki6k=
=t0E4
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python related mags

2006-06-12 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Now that is a real pity.

Wish I were talented enough to do it myself.



Mike Hansen wrote:
> On Jun 12, 2006, at 5:53 AM, Andrew Robert wrote:
> 
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> Hi everyone,
>>
>> Does anyone know of any Python related magazines available that would 
>> be
>> worth subscribing to?
>>
>> Ideally, a free one, but I would not object to a reasonably priced one
>> either.
>>
>> I was able to find pyzine located at www.pyzine.com but it appears to 
>> be
>>   defunct.
>>
>>
> I don' think there's much out  there. Sometime Linux Journal will have 
> Python related articles, sometimes Dr. Dobbs. As popular as Python is, 
> it's probably not popular enough to sustain a magazine devoted just to 
> it.
> 
> Mike
> 
> ___________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEjhFTDvn/4H0LjDwRAq14AJ9RzCA4o5pNW6y47c1mM/Tzm0R3EACfZ0ec
KxReJbvZERlj2gHx4Y+FB58=
=kKr8
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Odd traceback - invalid token when extracting contents of XML data element

2006-06-12 Thread Andrew Robert
Hi Everyone,

Attached are three scripts that I intend to use for transporting a file
via IBM's WebSphere MQSeries middle-ware.

The sender script uses a regular expression to replace characters not
[a-z][A-Z][0-9] or white space with their hex value equivalents.

The purpose of this is to make the contents of a transported file
viewable inside MQSeries queues.


The attached code works just fine for transporting ASCII text files but
it bombs with the following trace when run against binary files.

Does anyone know why this might be occurring?

Traceback (most recent call last):
  File "M:\MQ\MQ\Scripts\receiver.py", line 267, in ?
receiver.run()
  File "M:\MQ\MQ\Scripts\receiver.py", line 110, in run
self.get()
  File "M:\MQ\MQ\Scripts\receiver.py", line 139, in get
tree = ElementTree(file=buff)
  File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line
543, in __init__
self.parse(file)
  File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line
583, in parse
parser.feed(data)
  File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line
1242, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3,
column 39

I think that a particular character is perhaps not being translated to
ascii as required but I don't know which one it mught be.

Part of the reason for this encoding mechanism is so that it plays nice
with existing perl code already in place.

Not my choice, but what can you do.

Any help you can provide on this would be greatly appreciated.


-- 
Thank you,
Andrew Robert

#!c:\python24\python
# Program: sender.py
# Authors: Andrew Robert and Dariusz Suchojad
#
# Function: To send files to an MQSeries Queue via a server connection
#
#
# Module requirements not included with Python are ElementTree and Pymqi.
#
# Element tree can be found at http://effbot.org/downloads/#elementtree
#
# Pymqi can be found athttp://pymqi.sourceforge.net/
#
# Logging with tie-ins to the NT event viewer require the Python Windows 
# extensions located at 
http://sourceforge.net/project/showfikes.php?group_id=78018
#
# Conventions used in this program are that all queue managers and queues are 
upper case.
#
#
# VerDate   Programmer  Modification
# v1.0 - 05/09/06   AAR Initial release
# v1.1 - 05/10/06   AAR Change how file is opened to rb
# v1.2 - 05/11/06   AAR Modified to connect via server connections 
only
# v1.3 - 05/11/06   AAR Added requirement to specify destination 
file name 
# v1.4 - 05/11/06   AAR Change value test logic to prevent usage of
#   empty string values
#   Removed test for exception on qmgr connect
#   Converted certain comment lines to doc 
strings
# v1.5 - 05/13/06   AAR Added checksum generation of transmitted 
file
# v1.6 - 05/14/06   AAR Checksum generation enhanced to better 
handle 
#   large files 
# v1.7 - 05/15/06   AAR Added event logging to NT event application 
viewer.
#   This leverages built in date/time stamping 
as well
#   as presenting a central repository for all 
events
# v1.8 - 05/15/06   AAR update logging logic, removing if/elif/else 
conditions 
#   Added POSIX plaform support for logging 
events
# v1.9 - 05/16/06   AAR Add ability to take command options from 
input file
# v1.10 - 05/19/06  AAR Append python module library path to 
include ts-mqadm-d share
#   Farm out event logging, checksum, mailer to 
#   separate/reusable modules stored on 
ts-mqadm-d share
#   temporarily removed ability to send mail or 
validate addressing
# v1.11 - 05/19/06  AAR Move signal handling to external module and 
update code 
#   references
# v1.12 - 05/21/06  AAR Change file encoding from base64 to quopri 
methodology. 
#   Quopri is an encoding strategy based on RFC 
1521 for mime
# v1.13 - 05/22/06  AAR Revert encoding structure back to base64. 
quopri structure 
#   does not encode in XML well
# v1.14 - 05/22/06  AAR Determine if input file is ascii or binary. 
adjust encoding 
#   on file type
# v1.15 - 05/26/06  AAR Add import of custom file encoder function
#   remove import of base64 module
#   remove call to base64 encoder
#   modify content element creation so that i

[Tutor] Python related mags

2006-06-12 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi everyone,

Does anyone know of any Python related magazines available that would be
worth subscribing to?

Ideally, a free one, but I would not object to a reasonably priced one
either.

I was able to find pyzine located at www.pyzine.com but it appears to be
  defunct.



- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2

iD8DBQFEjVWhDvn/4H0LjDwRAtsnAJwJ6I6elkmzCwmJUNC3CxDPxjR3bQCeOwL6
IMxn+qVOqe4uwuaCrGA8Qww=
=hJPj
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to import a module which was not in the current working directory?

2006-05-26 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Linda,

You can append your path to include the location of the module.

An example of this would be:

sys.path.append(r'\\share\somedirectory')


linda.s wrote:
> Hi,
> How to import a module which was not in the current working directory?
> Thanks,
> Linda
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdxZUDvn/4H0LjDwRAovqAJ99tie7ZVJiFdHF/wnqxYGujBmhuQCdFWEw
fFa4k3xTnxwr/nPmuG8PW1Q=
=IVFd
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,


Thanks for all of your patience on this.

I finally got it to work.


Here is the completed test code showing what is going on.

Not cleaned up yet but it works for proof-of-concept purposes.



#!/usr/bin/python

import re,base64

# Evaluate captured character as hex
def ret_hex(value):
return '%'+base64.b16encode(value)

# Evaluate the value of whatever was matched
def enc_hex_match(match):
return ret_hex(match.group(0))

def ret_ascii(value):
return base64.b16decode(value)

# Evaluate the value of whatever was matched
def enc_ascii_match(match):

arg=match.group()

#remove the artifically inserted % sign
arg=arg[1:]

# decode the result
return ret_ascii(arg)

def file_encoder():
# Read each line, pass any matches on line to function for
# line in file.readlines():
output=open(r'e:\pycode\sigh.new','wb')
for line in open(r'e:\pycode\sigh.txt','rb'):
 output.write( (re.sub('[^\w\s]',enc_hex_match, line)) )
output.close()


def file_decoder():
# Read each line, pass any matches on line to function for
# line in file.readlines():

output=open(r'e:\pycode\sigh.new2','wb')
for line in open(r'e:\pycode\sigh.new','rb'):
output.write(re.sub('%[0-9A-F][0-9A-F]',enc_ascii_match, line))
output.close()




file_encoder()

file_decoder()
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdfQQDvn/4H0LjDwRAnbIAJ0cD9fdtIqtpfksP07n02Er9YMPiwCfTSsC
pCVDgnQ8pbZS40BuA8gNNBQ=
=mPoG
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Kent,


Sorry for causing so much trouble.

I am not married to either a single or multi-line solution one way or
another.


Just a solution that works.

Based on something by Danny Yoo provided, I had started with something like:



import re,base64

# Evaluate captured character as hex
def ret_hex(value):
return base64.b16encode(value)

def ret_ascii(value):
return base64.b16decode(value)

# Evaluate the value of whatever was matched
def eval_match(match):
return ret_ascii(match.group(0))


out=open(r'e:\pycode\sigh.new2','wb')

# Read each line, pass any matches on line to function for
# line in file.readlines():
for line in open(r'e:\pycode\sigh.new','rb'):
print (re.sub('[^\w\s]',eval_match, line))



The char to hex pass works but omits the leading x.

The hex to char pass does not appear to work at all.

No error is generated. It just appears to be ignored.



Kent Johnson wrote:
> Andrew Robert wrote:



> 
> You have an argument in the wrong place. Stop trying to do everything in 
> one line! Put the lambda in a def'd function. Put the re.sub on it's own 
> line. You are tripping over unnecessary complexity. I'm not going to fix 
> it any more.
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEddHSDvn/4H0LjDwRAibnAJ4/6/IiPtz7k+jIa01kRe1X25UNkACfaq24
bbqKqyOZyLpCRBEHbrO7H7A=
=8+rq
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

lol..


Glutton for punishment I guess.

I tried removing the last parentheses but I then get an error that two
arguments are passed when three are expected.



Danny Yoo wrote:
> 
> 
>> for line in open(r'e:\pycode\out_test.txt','rb') :
>>output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
>> 16))) % ord(s.group()), line))
> 
> 
> Let's add some whitespace.
> 
> output.write(re.sub(r'([^\w\s])',
>lambda s: chr(
>   int(s.group(), 16)
> )
>  ) % ord(s.group()), line))
> 
> I do see at least one too many parens here, so that's something you
> should look at.
> 
> But I'd also recommend writing a helper function here.  Just because you
> can do this in one line doesn't mean you have to.  *grin* It might be
> useful to change the lambda back to a helper function.
> 

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdbtlDvn/4H0LjDwRAqg+AJ0SZY/T3kCpG+3qWX3F3yRSt73P7ACdFsZQ
LnBhWh95EfuHA+eMkz6gkF4=
=C0oN
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

When I alter the code to:

import re,sys

output = open(r'e:\pycode\new_test.txt','wb')

for line in open(r'e:\pycode\out_test.txt','rb') :
   output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16)))
, line)

output.close()

I get the trace:

Traceback (most recent call last):
  File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8, in ?
output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
16))) , line)
TypeError: sub() takes at least 3 arguments (2 given)

It appears that the code is not recognizing the line.

I checked the parentheses and they appear to be properly enclosed.

Any ideas?

Kent Johnson wrote:




> Take out " % ord(s.group())" - the result of chr() is the actual string 
> you want, not a format string.
> 
> The syntax error is caused by mismatched parentheses.
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdbpWDvn/4H0LjDwRAhEmAJ9WSfKitH1VgsTD5kTLI4cWP5YZRwCgs0mz
Y9jl5l6Q/VZe6NmUaibZGa4=
=nezG
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi all,

I tried:


output = open(r'e:\pycode\new_test.txt','wb')

for line in open(r'e:\pycode\out_test.txt','rb') :
output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
16))) % ord(s.group()), line))


This generated the traceback:

File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8
output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
16))) % ord(s.group()), line))

 ^
SyntaxError: invalid syntax


By any chance, do you see where the syntax issue is?


Kent Johnson wrote:
> Andrew Robert wrote:




> Use int(s, 16) to convert a base 16 string to an integer, and chr() to
> convert the int to a string. So something like this:
> lambda s: chr(int(s.group(), 16)))
> 
> Kent
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdbMrDvn/4H0LjDwRAi09AKC1I6XIcXiqYmpk4hpcbnkwux1NawCgt/zp
xySHXPrh5JncZphAcVRtbtI=
=xtr9
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Great!

Taking this a little further along, I wrote the converted file to a new
file using:


import re,sys

output = open(r'e:\pycode\out_test.txt','wb')

for line in open(r'e:\pycode\sigh.txt','rb') :
output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' %
ord(s.group()), line))

output.close()


Not elegant but its strictly for test :)


Last part and we can call it a day.

How would you modify the lambda statement to covert a the hex value back
to its original value?


Do I need to incorporate base64.16basedecode somehow?

The original perl code to covert back to normal is:

`perl -ple 's/(?:%([0-9A-F]{2}))/chr hex $1/eg' somefiletxt



Kent Johnson wrote:
> Yes, this is a feature of print, it always inserts a newline. To avoid 
> this, use sys.stdout.write() instead of print:
> for line i open(r'e:\pycode\sigh.txt','rb'):
>  line = re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)
>  sys.stdout.write(line)
> 
> Kent
> 




- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdacCDvn/4H0LjDwRAkTWAJ4/KS6WnAgUraPZLmyPCQ45izq5tQCgl7sR
nkZbIauRcdlavA89ZhnDSuM=
=YZPS
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-25 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone


I did a comparison of the output between the perl and python methodology.

They do basically the same thing but the perl form seems to be more "true"

The python method inserts extra blank lines after each hex value line.

For example:

Original text:

def handler(signal, frame):
"""
Trap signal interrupts if they occur
"""

Converted In Perl:

def handler%28signal%2C frame%29%3A
%22%22%22
Trap signal interrupts if they occur
%22%22%22


Converted In Python:

def handler%28signal%2C frame%29%3A

%22%22%22

Trap signal interrupts if they occur

%22%22%22

Does anyone know why this might be?

Is the print statement inserting a artificial new line character?

If so, how cam I remove that?


The python code I am using is:



import re,sys

for line i open(r'e:\pycode\sigh.txt','rb'):
print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)



The file is being opened in rb mode because eventually binary files
would be opened via this method as well.



Alan Gauld wrote:
>> a = open(r'e:\pycode\csums.txt','rb').readlines()
>>
>> for line in a:
>>print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)
> 
> Or just
> 
> for line in open(r'e:\pycode\csums.txt','rb'):
>   print.
> 
>> Breaking down the command, you appear to be calling an un-named function
>> to act against any characters trapped by the regular expression.
>>
>> Not familiar with lamda :).
> 
> You ae absolutely right.
> It creates an un-named(or anonymous function). :-)
> 
>> The un-named function does in-place transformation of the character to
>> the established hex value.
> 
> Its actually the call to re.sub() that makes in in place.
> 
>> How would you reverse the process from a python point of view?
> 
> Just write a reverse function for the lamda...
> 
> Alan G.
> 
> 

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdZ9oDvn/4H0LjDwRAo89AJwJ64+wpfOnboxw4/+w8PhmZBzgwACfYH7C
VPW5VPyqSWhAUgkoOBorjJM=
=bOj0
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2006-05-24 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Wow!!..

That awesome!


My goal was not to make it a one-liner per-se..

I was simply trying to show the functionality I was trying to duplicate.

Boiling your one-liner down into a multi-line piece of code, I did:

#!c:\python24\python

import re,sys

a = open(r'e:\pycode\csums.txt','rb').readlines()

for line in a:
print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)


Breaking down the command, you appear to be calling an un-named function
to act against any characters trapped by the regular expression.

Not familiar with lamda :).

The un-named function does in-place transformation of the character to
the established hex value.


Does this sound right?

If I then saved the altered output to a file and wanted to transform it
back to its original form, I would do the following in perl.


perl -ple 's/(?:%([0-9A-F]{2}))/chr hex $1/eg' somefiletxt

How would you reverse the process from a python point of view?





Karl Pflästerer wrote:
> python -c "import re, sys;print re.sub(r'([^\w\s])', lambda s: '%%%2X' % 
> ord(s.group()), sys.stdin.read())," < somefile
> 
> It's not as short as the Perl version (and might have problems with big
> files). Python does not have such useful command line switches like -p
> (but you doesn't use Python so much for one liners as Perl) but it does
> the same ; at least in this special case (Python lacks something like the
> -l switch).
> 
> With bash it's a bit easier. (maybe there's also a way with cmd.com to
> write multiple lines)?
> 
> $ python -c "import re,sys
> for line in sys.stdin: print re.sub(r'([^\w\s])', lambda s: '%%%2X' % 
> ord(s.group()), line)," < somefile
> 
> 
>Karl

- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdPFwDvn/4H0LjDwRAuzuAKCOPja9Js1ueP2GoT+B0hoFubDEegCguzfT
QL87gmKUx6znmGQxXqg6V+A=
=7MT2
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hex conversion strangeness

2006-05-24 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,

I am trying to understand conversion of a value to hex.

Could you please confirm that what I am doing is right?

Get the hex value of ! and store it in a

a=hex(ord('!'))
print a
0X21

I see examples including this kind of a statement but I am not sure why.

int(a,16)
33

If the 0X21 is the actual hex value, then why convert to integer?

Is this the ASCII table reference to the hex value?


- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdNoTDvn/4H0LjDwRAp6yAKC5wI55jX5BJeu89ahj55hA7i8eAQCgu2Op
rVbo0kgQ9GQv8N0TB34StlY=
=pe50
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question on regular expressions

2006-05-24 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,


I have two Perl expressions


If windows:

perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge"  somefile.txt

If posix

perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge'  somefile.txt



The [^\w\s]  is a negated expression stating that any character
a-zA-Z0-9_, space or tab is ignored.

The () captures whatever matches and throws it into the $1 for
processing by the sprintf

In this case, %%%2X which is a three character hex value.

How would you convert this to a python equivalent using the re or
similar module?

I've begun reading about using re expressions at
http://www.amk.ca/python/howto/regex/ but I am still hazy on implementation.

Any help you can provide would be greatly appreciated.


- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEdIoKDvn/4H0LjDwRAi24AKDFmRohKFfp13z/M9c8O1LQElGzMgCglcRw
3ERK7FxWejsuFcnDSNdOYjM=
=28Lx
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with class - get message that self is not defined

2006-05-22 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,


When I try to use the class listed below, I get the statement that self
is not defined.

test=TriggerMessage(data)
var = test.decode(self.qname)

I would have thought that self would have carried forward when I grabbed
an instance of TriggerMessage.

Any ideas on this?



The class in question is:


class TriggerMessage(object):

def __init__(self,data):
"""
Unpacks the passed binary data based on the MQTCM2 format 
dictated in
the MQ Application Programming Reference
"""

self.data=data
self.structid=None
self.version=None
self.qname=None
self.procname=None
self.trigdata=None
self.appltype=None
self.applid=None
self.envdata=None
self.userdata=None
self.qmgr=None


def decode(self):
import struct
format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s'
size=struct.calcsize(format)
self.data=data  
self.structid, self.version, self.qname, self.processname,  
 \
self.triggerdata, self.appltype, self.applid,   
 \
self.envdata, self.userdata, self.qmgr  
 \
= struct.unpack(format,self.data)



- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEcgK6Dvn/4H0LjDwRArwJAKCVdcpLC7IcUzDaMN+L/hVFv8CToQCaA6hP
0KteYe8olY5/72+uktGRCco=
=ToBq
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with a class

2006-05-22 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,

I am getting an odd traceback when using a class.

The class I am using is

class TriggerMessage:

def __init__(self,data):
"""
Unpacks the passed binary data based on the MQTCM2

format dictated in
the MQ Application Programming Reference
"""

self.data=data
self.structid=None
self.version=None
self.qname=None
self.procname=None
self.trigdata=None
self.appltype=None
self.applid=None
self.envdata=None
self.userdata=None
Self.qmgr=None


def decode(self):
format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s'
size=struct.calcsize(format)

self.structid, self.version, self.qname, self.processname,  
 \
self.triggerdata, self.appltype, self.applid,   
 \
self.envdata, self.userdata, self.qmgr  
 \
= struct.unpack(format,self.data)


When I try to reference the class with the following statement:

test = TriggerMessage.decode(data)

I get the following traceback

Traceback (most recent call last):
  File "m:\mq\mq\scripts\receiver.py", line 238, in ?
test = TriggerMessage.decode(data)
TypeError: unbound method decode() must be called by TriggerMessage
instance as first argument (got str instance instead)

Does this make any sense?

The variable data passed to the class is valid and is used elsewhere
correctly.


- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone:   617-954-5882

E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEcfV4Dvn/4H0LjDwRAo9XAJ4viu2SxR50Mgl4DWucJs0+l84r+gCgkcMy
xs+li5sUfKpz1fgAPw5PhuE=
=9IHp
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] File encoding strategy question

2006-05-20 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi everyone,

I am in the process of creating a file transmit/receiver program using
MQSeries.

The way it works is through creation of an XML message.

Elements within the XML message contain things such as file name, size,
and the file contents.

The file contents are encoded, currently using Base64, for support of
both binary and text data.

This works great but there is a small rub to the problem.

I would like to be able to view the contents of the file if it is text
while still maintaining the ability to transmit binary data.

Does anyone know of an encoding format that would make this possible?

The viewing of the file contents does not need to be perfect, merely
enough that a particular in-transit file could be identified.

Thoughts on this would be greatly appreciated.


- --
Thank you,
Andy

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEb42PDvn/4H0LjDwRAq7DAKC4o5NwKOx9vDYB71C0hcoRiyDIuQCgrQVE
4s4r2BnmgAR728PuZow6vHU=
=RT23
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Solution found for option parser

2006-05-16 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi everyone,

Just to be complete, I figured I would share the solution to use option
parser for both command line and configuration file option passing.

I hope it may be of use to someone in the future.


parser = OptionParser()

if len(sys.argv) == 2:
lines = open(sys.argv[1],"rb").readlines()
for line in lines:
line=line.strip()
if not line:
continue
short, long, dest, help, default = line.split(";")
help = "\t\t" + help # Prepend tabs to help message
parser.add_option(short, long, dest=dest, help=help, 
default=default)
else:
parser.add_option("-m","--qmanager", dest="qmanager",
help="\t\tQueue Manager to inquire against"),
parser.add_option("-q","--queue", dest="queue",
help="\t\tQueue the message will be sent to"),
parser.add_option("-d","--dest", dest="dest",
help="\t\tDestination File Name"),
parser.add_option("-f", "--file",
action="store", type="string", dest="filename",
help="File to be transmitted", metavar="FILE")

(options, args) = parser.parse_args()


thanks all for the insight
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEanTrDvn/4H0LjDwRAmt0AJ4jf84OXoNdrxzz+A/pdKgiPnhyAwCfZQrG
QCuhjN8sbYq+WhzmLToKIZs=
=nOFN
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on option parser

2006-05-16 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Kent,

If I understood correctly, you meant something like this?


#
# Parse command line options and automatically build help/usage
# display
#
if len(sys.argv) == 2:
infile= open(sys.argv[1],"rb").read()
parser=OptionParser()
(options, args) = parser.parse_args(infile)
else:
parser = OptionParser()

parser.add_option("-m","--qmanager", dest="qmanager",
help="\t\tQueue Manager to inquire against"),
parser.add_option("-q","--queue", dest="queue",
help="\t\tQueue the message will be sent to"),
parser.add_option("-t","--to", dest="mto",
help="\t\taddress any mail messages will be sent to")
(options, args) = parser.parse_args()

print options.qmanager


If so, the code generates the following deletion error.

Traceback (most recent call last):
  File "C:\Documents and Settings\Andrew Robert\My
Documents\receiver.py", line 326, in ?
(options, args) = parser.parse_args(infile)
  File "C:\Python24\lib\optparse.py", line 1275, in parse_args
stop = self._process_args(largs, rargs, values)
  File "C:\Python24\lib\optparse.py", line 1322, in _process_args
del rargs[0]
TypeError: object doesn't support item deletion


Any ideas?

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEahcFDvn/4H0LjDwRAkZFAKCGapybjYnhuX9dy1DvMswskawLegCdEbbY
o/VaV2WP/ymg3dbwo3TaBi4=
=wLEn
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question on option parser

2006-05-16 Thread Andrew Robert
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Everyone,

I have a program that I'd would like to enhance flexibility in calling.

Is there a way to leverage optionparser so it can accept input from both
command line and a configuration file?

Current code block is:

#
# Parse command line options and automatically build
# help/usage display
#
parser = OptionParser()
parser.add_option("-m","--qmanager", dest="qmanager",
help="\t\tQueue Manager to inquire against"),
parser.add_option("-q","--queue", dest="queue",
help="\t\tQueue the message will be sent to"),
parser.add_option("-t","--to", dest="mto",
help="\t\taddress any mail messages will be sent to")
(options, args) = parser.parse_args()

Any help you can provide on this would be greatly appreciated.

Thanks,
Andy
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.3 (MingW32)

iD8DBQFEaf5xDvn/4H0LjDwRAnzAAJ94RcBxTxARkvX5pwMtvVM9n/vntgCfZ1bV
FvMSiQpo/2EneM9hvuxpCi8=
=2Il4
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor