Re: [Tutor] Mod_python greedy url matching

2005-10-05 Thread Danny Yoo


On Wed, 5 Oct 2005, Jay Loden wrote:

> I'm having trouble with Apache and Mod_python - mod_python is set to use
> /var/www/html and pass all *.htm files on to the handler I wrote.
> Unfortunately, mod_python does a greedy match, so
> /var/www/html/subdirectory/file.htm still gets passed to the handler!
> Is there some way to limit the handler to the directory and NOT include
> subdirectories?

Hi Jay,

You may want to ask the Apache folks about this one.  Your question
specific enough that the Apache folks will probably be better at this one
than Python-Tutor.

If you strip your question to its essentials, it really is an Apache
configuration problem more than anything else; it really isn't related to
Python except from the tangential relation to mod_python.  The behavior
you're seeing is how Apache deals with all Directory-specific directives:
subdirectories "acquire" the properties of their parent directory.

But from the notes in:

http://httpd.apache.org/docs/2.0/sections.html
http://httpd.apache.org/docs/2.0/mod/core.html#directory
http://httpd.apache.org/docs/2.0/mod/mod_mime.html#removehandler

it sounds possible for you to apply a RemoveHandler directive on the
subdirectories of whatever parent directory you're trying not to handle.

However, since we're really straying away from programming topics and into
web-server system administration, I'd strongly recommend continuing this
question on a mailing list like the one listed in:

http://httpd.apache.org/lists.html#http-users

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


[Tutor] Line continuation with readlines

2005-10-05 Thread Craig MacFarlane

Hello,

Is there a way to make line continuation work with
the readlines function?

i.e.

  this is \
one line.

Thank you,
Craig




__ 
Yahoo! for Good 
Donate to the Hurricane Katrina relief effort. 
http://store.yahoo.com/redcross-donate3/ 

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


Re: [Tutor] Beautiful soup

2005-10-05 Thread Oliver Maunder
On 10/4/05, Andrew P <[EMAIL PROTECTED]> wrote:
Oops, Paul is probably right.  I thought urllib2 opened local
files in the absence of an identifier like "http://".  Bad assumption on my part.  I remembered that
behavior from somewhere else, maybe urllib.

The following function could be useful here - I got it from Dive Into
Python -
http://diveintopython.org/scripts_and_streams/index.html#kgp.openanything

It tries to open a file with urllib, and if that fails it uses open():
def openAnything(source):  # try to open with urllib (if source is http, ftp, or file URL)
import urllib try:  return urllib.urlopen
(source)  except (IOError, OSError):pass  
# try to open with native open function (if source is pathname)try:  return open(source)
except (IOError, OSError):pass  
# treat source as stringimport StringIO   return StringIO.StringIO(str(source))

Olly

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


[Tutor] Help Needed

2005-10-05 Thread Steve Haley








Hello,

 

I am trying to learn Python which I am brand new to.  I have
run into a problem that I would appreciate help with.

 

When I am in Python Shell of the IDLE GUI, when I click
Edit/Run Script, I am getting a dialog box that is titled “Not saved”
and states “The buffer for Python shell is not saved.  Please save it
first.” With an “OK” button that just takes me back to the
Shell window.  I am going through a book (which suggests this resource as a
good place to ask questions) and Edit/Run Script was working just fine the
other day.  

 

I don’t have a clue what is wrong or how to fix it.  I
have searched the Python.org website but was unable to find any reference to
this.  Any help would be greatly appreciated.

 

Thanks very much,

Steve

[EMAIL PROTECTED]






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


Re: [Tutor] Line continuation with readlines

2005-10-05 Thread Danny Yoo


On Mon, 3 Oct 2005, Craig MacFarlane wrote:

> Is there a way to make line continuation work with
> the readlines function?
>
> i.e.
>
>   this is \
> one line.

Hi Craig,

readline() doesn't look at the content of lines, so no, not out of the
box.  However, would it be satisfactory if you wrote a function to define
that behavior?


Good luck to you!

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


Re: [Tutor] FW: Help Needed

2005-10-05 Thread Daniel Watkins

When I am in Python Shell of the IDLE GUI, when I click Edit/Run
Script, I am getting a dialog box that is titled “Not saved” and
states “The buffer for Python shell is not saved.  Please save
it first.” With an “OK” button that just takes me back to the
Shell window.  I am going through a book (which suggests this
resource as a good place to ask questions) and Edit/Run Script
was working just fine the other day.  

Go to File > Save As... and save the file somewhere. Then attempt to run
the script. If this still doesn't work, I'm stumped, but it really
should...

Dan


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


Re: [Tutor] Help Needed

2005-10-05 Thread Pujo Aji
hi,
 
make sure in the 
option/general/Startup preferences/at startup/open edit windowoption/general/Startup preferences/autosave preferences/NoPrompt
 
run the program by clicking F5
 
Cheers,
pujo 
On 10/5/05, Steve Haley <[EMAIL PROTECTED]> wrote:


Hello,
 
I am trying to learn Python which I am brand new to.  I have run into a problem that I would appreciate help with.
 
When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, I am getting a dialog box that is titled "Not saved" and states "The buffer for Python shell is not saved.  Please save it first." With an "OK" button that just takes me back to the Shell window.  I am going through a book (which suggests this resource as a good place to ask questions) and Edit/Run Script was working just fine the other day.  

 
I don't have a clue what is wrong or how to fix it.  I have searched the 
Python.org website but was unable to find any reference to this.  Any help would be greatly appreciated.
 
Thanks very much,
Steve
[EMAIL PROTECTED]
___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] need help to understand terms for desinging a program

2005-10-05 Thread Hameed U. Khan
Hi,
  I need to make a program which will accomplish following. I dont
need the code. I want to make it myself. But I need guidance from you
people because I am not a good programmer. I need help in
understanding following terms.

   " qmail-queue  reads  a  mail message from descriptor 0.  It
   then reads envelope information  from  descriptor  1.   It
   places  the  message  into  the  outgoing queue for future
   delivery by qmail-send.

   The envelope information is  an  envelope  sender  address
   followed  by  a list of envelope recipient addresses.  The
   sender address is preceded by the letter F and  terminated
   by  a  0  byte.  Each recipient address is preceded by the
   letter T and terminated by a 0 byte.  The list of  recipi-
   ent addresses is terminated by an extra 0 byte.  If qmail-
   queue sees end-of-file before the extra 0 byte, it  aborts
   without placing the message into the queue."

 I want to inspect messages before passing them to actuall qmail-queue
program.
Thanks in advance for your help.
--
Regards,
Hameed U. Khan
Registered Linux User #: 354374
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help to understand terms for desinging a program

2005-10-05 Thread paul brian
This is a pretty big question, and it would be easier to answer if you
can give us more details about what you want to do.

It seems you want to inspect outgoing mails (possibly rewrite their
addresses?) before the mails are sent out.

If you are looking to send out emails to a list then I suggest looking
at mailman - a python mailing list manager.

If you want to use python to examine mail messages and do not care
what mailserver (MTA) you use you could try exim instead of qmail and
then try exim-python. 
http://botanicus.net/dw/exim-python/exim-4.32py1.html





On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote:
> Hi,
>  I need to make a program which will accomplish following. I dont
> need the code. I want to make it myself. But I need guidance from you
> people because I am not a good programmer. I need help in
> understanding following terms.
>
>   " qmail-queue  reads  a  mail message from descriptor 0.  It
>   then reads envelope information  from  descriptor  1.   It
>   places  the  message  into  the  outgoing queue for future
>   delivery by qmail-send.
>
>   The envelope information is  an  envelope  sender  address
>   followed  by  a list of envelope recipient addresses.  The
>   sender address is preceded by the letter F and  terminated
>   by  a  0  byte.  Each recipient address is preceded by the
>   letter T and terminated by a 0 byte.  The list of  recipi-
>   ent addresses is terminated by an extra 0 byte.  If qmail-
>   queue sees end-of-file before the extra 0 byte, it  aborts
>   without placing the message into the queue."
>
>  I want to inspect messages before passing them to actuall qmail-queue
> program.
> Thanks in advance for your help.
> --
> Regards,
> Hameed U. Khan
> Registered Linux User #: 354374
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
--
Paul Brian
m. 07875 074 534
t. 0208 352 1741
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: Help Needed

2005-10-05 Thread Alan Gauld
> When I am in Python Shell of the IDLE GUI, when I click Edit/Run

You shouldn't be running scripts when in the shell, it executes them 
immediately.
You use edit/run when working in a script file window.

HTH,

Alan G 

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


[Tutor] How to strip both single and double quotes

2005-10-05 Thread Dick Moores
I'm writing a script that takes any text and outputs to a file a list of 
duples (k, word) where k is the number of occurrences of word in the text.

The text will contain "words" beginning or ending with non-alphabetic 
characters. To strip them off I use string.strip([chars]). My question is 
how to use strip just once to get rid of both kinds of quotes, single and 
double. It seems necessary to do it something like this:

# L is the original list of "words" in the text.
newL = []
for word in L:
 word = lower(word)
 newWord = word.strip(".,!?;:&*'=->http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to prevent ftplib from locking my script

2005-10-05 Thread Kent Johnson
Andrew P wrote:
> Normally I wouldn't pipe up here because threads really can be very 
> tricky.  But check out:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883
> 
> I use this recipe, originally from "Python in a Nutshell", all the time, 
> to solve exactly your problem.  Slow network stuff that I don't have 
> to/want to babysit.

There are also several recipes showing how to use a worker thread from a GUI 
program, for example this one:

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

Kent

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


Re: [Tutor] Help Needed

2005-10-05 Thread Kent Johnson
Steve Haley wrote:

> When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, 
> I am getting a dialog box that is titled “Not saved” and states “The 
> buffer for Python shell is not saved.  Please save it first.” With an 
> “OK” button that just takes me back to the Shell window.  I am going 
> through a book (which suggests this resource as a good place to ask 
> questions) and Edit/Run Script was working just fine the other day. 

This sounds kind of strange. I don't see an Edit / Run Script menu in IDLE for 
Python 2.3 or 2.4. I have a Run / Run Module command that is only available in 
the edit windows, not in the shell.

What version of Python are you using? Maybe you have a version with this menu. 
Normally you don't run directly from the shell window, it is for typing in 
commands interactively. You should open a new window and do your editing there.

Danny Yoo has a good introduction to IDLE here:
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html

Kent

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


[Tutor] htmllib

2005-10-05 Thread Ed Singleton
I want to dump a html file into a python object.  Each nested tag
would be a sub-object, attributes would be properties.  So that I can
use Python in a similar way to the way I use JavaScript within a web
page.

I looked at htmllib, but the documentation seems quite limited, and as
far as I can tell, I would have to write code for every single
potential tag in my page.

Is there a way to do this, or access the DOM through Python or something?

Thanks

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


Re: [Tutor] How to strip both single and double quotes

2005-10-05 Thread Alan Gauld
> how to use strip just once to get rid of both kinds of quotes, single and 
> double. It seems necessary to do it something like this:

JUst escape the quote character:

s.strip('\'"')

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] htmllib

2005-10-05 Thread Kent Johnson
Ed Singleton wrote:
> I want to dump a html file into a python object.  Each nested tag
> would be a sub-object, attributes would be properties.  So that I can
> use Python in a similar way to the way I use JavaScript within a web
> page.

I don't know of a way to run Python from within a web page. But if you want to 
fetch an HTML page from a server and work with it (for example a web-scraping 
app), many people use BeautifulSoup for this. If you have well-formed HTML or 
XHTML you can use an XML parser as well but BS has the advantage of coping with 
badly-formed HTML.
http://www.crummy.com/software/BeautifulSoup/

Kent

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


Re: [Tutor] How to strip both single and double quotes

2005-10-05 Thread Mark Thomas
On 10/5/05, Dick Moores <[EMAIL PROTECTED]> wrote:
> The text will contain "words" beginning or ending with non-alphabetic
> characters. To strip them off I use string.strip([chars]). My question is
> how to use strip just once to get rid of both kinds of quotes, single and
> double. It seems necessary to do it something like this:

Not sure what you mean by 'words' but how about something like this.
[x.strip('\' \" () * & ^ % $ # < ') for x in word.split()]

Example:
>>> str = 'this has special characters \" \' ()*&^%$# << '
>>> [x.strip('\' \" () * & ^ % $ # < ') for x in str.split()]
['this', 'has', 'special', 'characters', '', '', '', '']

--
 _
( ) Mark Thomas ASCII ribbon campaign
 X www.theswamp.org   - against HTML email
/ \
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] htmllib

2005-10-05 Thread Ed Singleton
You're like some kind of god!

That's exactly what I need.

Thanks

Ed

On 05/10/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Ed Singleton wrote:
> > I want to dump a html file into a python object.  Each nested tag
> > would be a sub-object, attributes would be properties.  So that I can
> > use Python in a similar way to the way I use JavaScript within a web
> > page.
>
> I don't know of a way to run Python from within a web page. But if you want 
> to fetch an HTML page from a server and work with it (for example a 
> web-scraping app), many people use BeautifulSoup for this. If you have 
> well-formed HTML or XHTML you can use an XML parser as well but BS has the 
> advantage of coping with badly-formed HTML.
> http://www.crummy.com/software/BeautifulSoup/
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to strip both single and double quotes

2005-10-05 Thread Dick Moores
Alan Gauld wrote at 04:38 10/5/2005:
> > how to use strip just once to get rid of both kinds of quotes, single 
> and
> > double. It seems necessary to do it something like this:
>
>JUst escape the quote character:
>
>s.strip('\'"')

That did it!

Thanks,

Dick Moores

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


Re: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help

2005-10-05 Thread Kent Johnson
Michael Cotherman wrote:
> I am a noob to converting pointers in C++ to arrays in
> python, although the first time I see it done, I will
> have no problem. Can you help converting the below
> (what I think is the 'decoder' section) to python?

OK I'll bite. Your code is copying from a src buffer to a dst buffer. The src 
buffer has a count byte followed by count-1 bytes of data. If the count is less 
that 0xFF, a zero byte has to be inserted into the dst. So the decode loop gets 
a count, copies that many bytes to the dst buffer, then optionally appends a 0.

Python doesn't have a direct equivalent to this sort of manipulation of memory 
pointers and raw memory buffers. They are commonly replaced by strings or 
lists. My function takes a string as an input argument, builds the output as 
string fragments in a list, then builds a string to return.

Note that Python strings include an implicit length so there is no need to pass 
and return a length argument.

I included a test case with the data from your previous email. Your data is 
evidently hex-encoded as well as COBS encoded - in other words your strings are 
hex values where each two chars represent a single byte. I have converted to 
and from byte strings to feed this to the decoder.

Kent

PS Please send your replies to the whole list, not to me personally. Thanks!


def unstuff(src):
# src is a COBS compressed string
current = 0 # index into src
dst = []# a list that will build the result

while current < len(src):
# Get the count and convert it to an integer
count = ord(src[current])

# Append count-1 chars from src to dst
dst.append(src[current+1:current+count])

# Do we need to add a zero byte?
if count < 0xFF:
dst.append('\x00')

# Bump the counter and continue
if count>0:
current += count
else:
current += 1

# dst is a list of string fragments; this converts it to a single string
return ''.join(dst)

def hexToString(hexStr):
''' Convert a string of two-digit hex values to a string of bytes with 
those values '''
return ''.join([chr(int(hexStr[i:i+2], 16)) for i in range(0, len(hexStr), 
2)])

def stringToHex(src):
''' Convert a byte string to a string of two-digit hex values '''
return ''.join([ '%02x' % ord(s) for s in src ])


if __name__ == '__main__':
data = '0002860104DB203F0100'
print data
data = hexToString(data)
print

newData = unstuff(data)
print stringToHex(newData)


> UINT CCobsPackets::UnStuffData(unsigned char *src,
> unsigned char *dst, UINT length)
> {
>   unsigned char *dstStart = dst;
>   unsigned char *end = src + length;
> 
>   while (src < end)
>   {
>   int i, code = *src++;
> 
>   for (i=1; i   {
>   *dst++ = *src++;
>   }
>   
>   if (code < 0xFF) 
>   {
>   *dst++ = 0;
>   }
>   }
> 
>   return (UINT)(dst - dstStart);
> }

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


[Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS) algorithm help]

2005-10-05 Thread Kent Johnson
Forwarding to the list

 Original Message 
Subject: Re: [Tutor] Consistant Overhead Byte Stuffing (COBS) algorithm help
Date: Tue, 4 Oct 2005 13:20:18 -0700 (PDT)
From: Michael Cotherman <[EMAIL PROTECTED]>
To: Kent Johnson <[EMAIL PROTECTED]>

Thanks for the response, the .NET code is really a
cluster, the whole cobs.cpp is below if needed. I
would think just by following the spec I could write a
cleaner program..



I am a noob to converting pointers in C++ to arrays in
python, although the first time I see it done, I will
have no problem. Can you help converting the below
(what I think is the 'decoder' section) to python?


even just comments to what is going on at each line...


-mike



UINT CCobsPackets::UnStuffData(unsigned char *src,
unsigned char *dst, UINT length)
{
unsigned char *dstStart = dst;
unsigned char *end = src + length;

while (src < end)
{
int i, code = *src++;

for (i=1; ipacketData){
delete [](delPacket->packetData);
delPacket->packetData = NULL;
}

delete delPacket;
}
}

while (!m_OutPacketList.IsEmpty())
{
ListPacket *delPacket = (ListPacket
*)m_OutPacketList.RemoveTail();

if (delPacket)
{
if (delPacket->packetData){
delete [](delPacket->packetData);
delPacket->packetData = NULL;
}


delete delPacket;
}
}
}

bool CCobsPackets::Init(HWND hwndDest, UINT nCobsMsg,
LPARAM lParam, UINT nMaxPacketSize)
{
m_hMsgWnd = hwndDest;
m_nCobsMsg = nCobsMsg?nCobsMsg:mg_nDefaultCobsMsg;
m_lParam   = lParam;
m_nMaxPacketSize = nMaxPacketSize;

m_nInPacketPos = 0;

if (m_pInPacketData){
delete []m_pInPacketData;
m_pInPacketData = NULL;
}

m_pInPacketData = new unsigned
char[m_nMaxPacketSize];
//TRACE0("create m_pInPacketData\n");

if (!m_pInPacketData)
return false;

return true;
}

ListPacket* CCobsPackets::NewPacket()
{
ListPacket *newPacket = NULL;

if (m_nMaxPacketSize)
{
newPacket = new ListPacket;
if (newPacket)
{
newPacket->packetData = new unsigned
char[m_nMaxPacketSize];

if (newPacket->packetData)
{
newPacket->packetLength = 0;
memset(newPacket->packetData, 0x00,
m_nMaxPacketSize);

}
else
{
delete newPacket;
newPacket = NULL;
}
}
}

return newPacket;
}

void CCobsPackets::SendEvent (EEvent eEvent, EError
eError)
{
// Post message to the client window

::PostMessage(m_hMsgWnd,m_nCobsMsg,MAKEWPARAM(eEvent,eError),LPARAM(m_lParam));
}

void CCobsPackets::DataReceived(unsigned char *src,
UINT length)
{
while (m_pInPacketData && length)
{
if (m_nInPacketPos < m_nMaxPacketSize)
{
if (*src == 0x00)
{
if (m_nInPacketPos)
{
ListPacket *decodePacket = NewPacket();

if (decodePacket)
{
decodePacket->packetLength =
UnStuffData(m_pInPacketData, decodePacket->packetData,
m_nInPacketPos);

m_InPacketList.AddTail(decodePacket);
decodePacket->packetCommand =
*(decodePacket->packetData);
SendEvent(EEventReceivedPacket);
}
else
{
// Unable to decode Packet Error
SendEvent(EEventPacketError,
EErrorPacketDecode);
}
}
else
{
// throw away zero-byte packets
}
memset(m_pInPacketData, 0x00, m_nMaxPacketSize);
m_nInPacketPos = 0;
}
else
   

Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]

2005-10-05 Thread Alan Gauld
> I am a noob to converting pointers in C++ to arrays in
> python, although the first time I see it done, I will
> have no problem. Can you help converting the below
> (what I think is the 'decoder' section) to python?

It won't be working code but I think this is whats happening...

> UINT CCobsPackets::UnStuffData(unsigned char *src,
> unsigned char *dst, UINT length)

def UnStuffData(src,dst,len):

> {
> unsigned char *dstStart = dst;
> unsigned char *end = src + length;

# I don't think these are needed for Pyhon.

> while (src < end)

for code in src:

> {
> int code = *src++;
> for (int i=1; i {
> *dst++ = *src++;
> }

for i in range(1,code):
   dst.append(i)

> if (code < 0xFF) 
> {
> *dst++ = 0;
> }

   if code < 0xff
   dst.append('\0')   # may not be needed in python...

> }
> return (UINT)(dst - dstStart);
> }

This looks odd, I don't think I understand what it does.
It seems to return an address thats potentially (probably?!)
before the start of the original dst...

I think it should probably translate to 
  return dst

Does that help?

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]

2005-10-05 Thread Kent Johnson
Alan Gauld wrote:
>> return (UINT)(dst - dstStart);
>> }
> 
> 
> This looks odd, I don't think I understand what it does.
> It seems to return an address thats potentially (probably?!)
> before the start of the original dst...

It's returning the length of dst.

Kent

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


Re: [Tutor] Line continuation with readlines

2005-10-05 Thread bob
At 07:20 PM 10/3/2005, Craig MacFarlane wrote:
>Hello,
>
>Is there a way to make line continuation work with
>the readlines function?
>
>i.e.

Do you mean e.g.?

>   this is \
> one line.

I assume the above is a 2 line file you wish to read using a file object's 
readlines method. There is nothing native to help you. I suggest you use 
the read method, then remove any sequence of \ followed by \n then split at \n.

input = file('c:/foo.txt').read()
input2 = input.replace('\\\n', '')
input3 = input2.split('\n')

Now you have a list of "logical" lines. Note there are no \n at the end. 
readlines leaves the \n at the end of the lines. 

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


Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]

2005-10-05 Thread Michael Cotherman
This is exactly what i was looking for

For those following, the \x00 added at the end of the
packet is just imaginary and represents

in the meantime, I made the following that just
'decobs' a series of packets (only 8-10 bytes) that
are coming in over the com port. (my incoming packets
also begin with x00 for some reason)

It accurately decodes that data stream (same result as
when I esc out and connect with the dev kit program)
I need to use what you have given me to make it
scalable for size 


#!/usr/bin/env python

#MJC 20051004
baudrate = 115200
port = 'com4'
echo = 1
convert_outgoing_cr = 1

import sys, serial, threading

s = serial.Serial(port,baudrate)

def reader():
"""loop forever and copy serial->console"""
cobspacket = [0,0,0,0,0,0,0,0,0,0]
while 1:
i = 0
cobschar = s.read()
cobspacket[i] = ord(cobschar)
if cobschar == '\x00':
cobschar = s.read()
cobspacket[i] = ord(cobschar)
codebyte = int(cobspacket[i])
while cobschar != '\x00':
if i == codebyte:
d = 0
codebyte = codebyte +
cobspacket[i] 
else:
d = cobspacket[i]

if i>0:
sys.stdout.write('%02X' % (d))

i+=1
cobschar = s.read()
cobspacket[i] = ord(cobschar)

sys.stdout.write('\n')

def writer():
"""loop forever and copy console->serial"""
while 1:
c = getkey()
if c == '\x1b': break   #exit on esc
s.write(c)  #send character
if convert_outgoing_cr and c == '\r':
s.write('\n')
if echo: sys.stdout.write('\n')


print "--- Mikey's interface --- type ESC to quit"
#start serial->console thread
r = threading.Thread(target=reader)
r.setDaemon(1)
r.start()
#enter console->serial loop
writer()

print "\n--- exit ---"



--- Alan Gauld <[EMAIL PROTECTED]> wrote:

> > I am a noob to converting pointers in C++ to
> arrays in
> > python, although the first time I see it done, I
> will
> > have no problem. Can you help converting the below
> > (what I think is the 'decoder' section) to python?
> 
> It won't be working code but I think this is whats
> happening...
> 
> > UINT CCobsPackets::UnStuffData(unsigned char *src,
> > unsigned char *dst, UINT length)
> 
> def UnStuffData(src,dst,len):
-snip-




__ 
Yahoo! for Good 
Donate to the Hurricane Katrina relief effort. 
http://store.yahoo.com/redcross-donate3/ 

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


Re: [Tutor] FW: Help Needed

2005-10-05 Thread Carroll, Barry
Alan is right.  According to section 3.5.2 of "Learning Python, 2nd
Edition", by David Ascher and Mark Lutz:

Run scripts from text edit windows, not the interactive window. To
run 
a file of code under IDLE, always select the Edit/RunScript menu 
option from within the text edit window where you are editing the
code 
to be run-not from within the main interactive window where the >>> 
prompt appears. The RunScript option should arguably not be
available 
in the interactive window at all (and in fact seems to have 
disappeared in the recent release); if you select it there, you'll 
wind up trying to run a log of your interactive session, with less 
than desirable results!

Regards,

Barry

>Date: Wed, 5 Oct 2005 10:44:09 +0100
>From: "Alan Gauld" <[EMAIL PROTECTED]>
>Subject: Re: [Tutor] FW:  Help Needed
>To: "Daniel Watkins" <[EMAIL PROTECTED]>, 
>Message-ID: <[EMAIL PROTECTED]>
>Content-Type: text/plain; format=flowed; charset="UTF-8";
>   reply-type=original
>
>> When I am in Python Shell of the IDLE GUI, when I click Edit/Run
>
>You shouldn't be running scripts when in the shell, it executes them 
>immediately.
>You use edit/run when working in a script file window.
>
>HTH,
>
>Alan G 


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


Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]

2005-10-05 Thread Michael Cotherman
def UnStuffData(src,dst,len):

   for code in src:
  for i in range(1,code):
  dst.append(i)

  if code < 0xff
  dst.append('\0') 

the above is the below code uncommented...
 it(and the original code) just seem to find the end
and puts a zero there...

I do not see the existing zeroes replaced. this is
kinda why I wanted to start from the specification...

here is how i see the laymans verson of the spec:


get a packet (or the first 254 bytes of it)

if 254 bytes, put an FF in front of them and send it
on its way as a 255 byte packet, repeat this until
less than 254 bytes remain.

Place a byte in front of the packet that is equal to
the count until the first x00 byte is found. At the
location where that x00 byte was, put the count until
the next x00 byte... and so on and so on...  (this is
where the imaginary x00 at the end comes in)

decoding is:
pop the first byte of the packet off and place
subsequent bytes into the output until you get to the
byte pointed to by the popped byte. When you reach
that byte, read its value as the new 'relative'
pointer, and copy x00 to the output. Proceed as above,
placing bytes to the output until the relative pointer
is reached or the end of the packet occurrs.

I guess I need to look if I wish for this part of the
program to handle the input as one big existing
string, or work on it a byte at a time as it comes in.
 

-mike c






--- Alan Gauld <[EMAIL PROTECTED]> wrote:

> > I am a noob to converting pointers in C++ to
> arrays in
> > python, although the first time I see it done, I
> will
> > have no problem. Can you help converting the below
> > (what I think is the 'decoder' section) to python?
> 
> It won't be working code but I think this is whats
> happening...
> 
> > UINT CCobsPackets::UnStuffData(unsigned char *src,
> > unsigned char *dst, UINT length)
> 
> def UnStuffData(src,dst,len):
> 
> > {
> > unsigned char *dstStart = dst;
> > unsigned char *end = src + length;
> 
> # I don't think these are needed for Pyhon.
> 
> > while (src < end)
> 
> for code in src:
> 
> > {
> > int code = *src++;
> > for (int i=1; i > {
> > *dst++ = *src++;
> > }
> 
> for i in range(1,code):
>dst.append(i)
> 
> > if (code < 0xFF) 
> > {
> > *dst++ = 0;
> > }
> 
>if code < 0xff
>dst.append('\0')   # may not be needed in
> python...
> 
> > }
> > return (UINT)(dst - dstStart);
> > }
> 
> This looks odd, I don't think I understand what it
> does.
> It seems to return an address thats potentially
> (probably?!)
> before the start of the original dst...
> 
> I think it should probably translate to 
>   return dst
> 
> Does that help?
> 
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] New Python book

2005-10-05 Thread Dick Moores
Magnus Lie Hetland's new book, _Beginning Python: From Novice to 
Professional_ was published by Apress on Sept. 26 (in the U.S.). Very 
much worth a look, IMHO. But what do the tutors think?



Dick Moores
[EMAIL PROTECTED]

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


[Tutor] Console output

2005-10-05 Thread Oliver Maunder
Does anyone know how I can update a line of console output without
creating a new line? I'm not explaning this too well, so here's an
example.

When you download a file with wget, the console display looks like this:

14%
[===>   
] 344,192  
16.28K/s    ETA 02:19

All the figures and the progress bar get continously updated. The only
way I know of sending output to the console is to use print or
sys.stdout.write(), but that would give me:
14%
[===>   
] 344,192  
16.28K/s    ETA 02:19
18%
[=>  
] 344,192  
16.28K/s    ETA 02:19
20% [>  

] 344,192  
16.28K/s    ETA 02:19

...and that's really not what I'm after!

Any help and ideas would be appreciated

Olly

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


Re: [Tutor] New Python book

2005-10-05 Thread Kent Johnson
Dick Moores wrote:
> Magnus Lie Hetland's new book, _Beginning Python: From Novice to 
> Professional_ was published by Apress on Sept. 26 (in the U.S.). Very 
> much worth a look, IMHO. But what do the tutors think?
> 
> 

This seems to be an update to his previous book, "Practical Python", rather 
than a completely new book. The TOC is almost identical. I haven't read the 
earlier book, either, so I don't have an opinion. The same sample chapter is 
available for each if anyone wants to compare. (see www.apress.com)

Kent

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


Re: [Tutor] New Python book

2005-10-05 Thread Andrew Fant
Kent Johnson wrote:
> Dick Moores wrote:
> 
>>Magnus Lie Hetland's new book, _Beginning Python: From Novice to 
>>Professional_ was published by Apress on Sept. 26 (in the U.S.). Very 
>>much worth a look, IMHO. But what do the tutors think?
>>
>>
> 
> 
> This seems to be an update to his previous book, "Practical Python", rather 
> than a completely new book. The TOC is almost identical. I haven't read the 
> earlier book, either, so I don't have an opinion. The same sample chapter is 
> available for each if anyone wants to compare. (see www.apress.com)
> 
> Kent

Has he at least changed the GUI chapters away from AnyGUI to one of the standard
toolkits?  The last edition would have been more use to me if it didn't do all
of its GUI programming in a toolkit that the author has removed from 
circulation.

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


Re: [Tutor] Console output

2005-10-05 Thread Christian Wyglendowski
 > -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On Behalf Of Oliver Maunder
> Sent: Wednesday, October 05, 2005 1:13 PM
> To: tutor@python.org
> Subject: [Tutor] Console output
> 
> Does anyone know how I can update a line of console output 
> without creating a new line? 

Hi Oliver,

If you are on a *nix system, check out the "curses" package in the
standard library.  I have never used it, but it provides ways to
accomplish what you are after.

HTH,

Christian
http://www.dowski.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Console output

2005-10-05 Thread Roel Schroeven
Oliver Maunder wrote:
> Does anyone know how I can update a line of console output without
> creating a new line? I'm not explaning this too well, so here's an example.
> 
> When you download a file with wget, the console display looks like this:
> 
> 14% [===>]
> 344,192   16.28K/sETA 02:19
> 
> All the figures and the progress bar get continously updated. The only
> way I know of sending output to the console is to use print or
> sys.stdout.write(), but that would give me:
> 14% [===>]
> 344,192   16.28K/sETA 02:19
> 18% [=>   ]
> 344,192   16.28K/sETA 02:19
> 20% [>]
> 344,192   16.28K/sETA 02:19
> 
> ...and that's really not what I'm after!
> 
> Any help and ideas would be appreciated

You need to:
- not write a newline
- backup to the beginning of the line

Simple example:

import sys
import time

def progress(n):
for i in range(n+1):
sys.stdout.write('\r%3s%% [%s>%s]' % (i, '='*i, ' '*(n-i)))
sys.stdout.flush()
time.sleep(0.5)

progress(60)

No newline is written, and the program backs up to the beginning of the
line using carriage return, '\r'. You can also put the carriage return
at the end of the line; the difference is that the cursor will be left
at the beginning of the line instead of at the end.

It's also possible to back up using backspaces ('\b'), but then you need
to count how many characters you wrote and use the equal amount of
backslashes.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven

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


Re: [Tutor] Console output

2005-10-05 Thread python-tutor

>>> import sys
>>> import time
>>> myList=range(10)
>>> for x in myList:
... sys.stdout.write(str(x) + "\r")
... sys.stdout.flush()
... time.sleep(1)

The "\r" causes a return without a newline feed.
Flush forces the text to be output (instead of getting buffered)

Enjoy!

Todd Maynard




On Wednesday 05 October 2005 02:13 pm, Oliver Maunder wrote:
> Does anyone know how I can update a line of console output without creating
> a new line? I'm not explaning this too well, so here's an example.
>
> When you download a file with wget, the console display looks like this:
>
> 14% [===> ] 344,192 16.28K/s ETA 02:19
>
> All the figures and the progress bar get continously updated. The only way
> I know of sending output to the console is to use print or
> sys.stdout.write(), but that would give me:
> 14% [===> ] 344,192 16.28K/s ETA 02:19
> 18% [=> ] 344,192 16.28K/s ETA 02:19
> 20% [> ] 344,192 16.28K/s ETA 02:19
>
> ...and that's really not what I'm after!
>
> Any help and ideas would be appreciated
>
> Olly
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help to understand terms for desinging a program

2005-10-05 Thread Hameed U. Khan
On 10/5/05, paul brian <[EMAIL PROTECTED]> wrote:
> This is a pretty big question, and it would be easier to answer if you
> can give us more details about what you want to do.
>
> It seems you want to inspect outgoing mails (possibly rewrite their
> addresses?) before the mails are sent out.
>
> If you are looking to send out emails to a list then I suggest looking
> at mailman - a python mailing list manager.
>
> If you want to use python to examine mail messages and do not care
> what mailserver (MTA) you use you could try exim instead of qmail and
> then try exim-python.
> http://botanicus.net/dw/exim-python/exim-4.32py1.html
>
>
>
>
>
> On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote:
> > Hi,
> >  I need to make a program which will accomplish following. I dont
> > need the code. I want to make it myself. But I need guidance from you
> > people because I am not a good programmer. I need help in
> > understanding following terms.
> >
> >   " qmail-queue  reads  a  mail message from descriptor 0.  It
> >   then reads envelope information  from  descriptor  1.   It
> >   places  the  message  into  the  outgoing queue for future
> >   delivery by qmail-send.
> >
> >   The envelope information is  an  envelope  sender  address
> >   followed  by  a list of envelope recipient addresses.  The
> >   sender address is preceded by the letter F and  terminated
> >   by  a  0  byte.  Each recipient address is preceded by the
> >   letter T and terminated by a 0 byte.  The list of  recipi-
> >   ent addresses is terminated by an extra 0 byte.  If qmail-
> >   queue sees end-of-file before the extra 0 byte, it  aborts
> >   without placing the message into the queue."
> >
> >  I want to inspect messages before passing them to actuall qmail-queue
> > program.
> > Thanks in advance for your help.
> > --
> > Regards,
> > Hameed U. Khan
> > Registered Linux User #: 354374
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> --
> --
> Paul Brian
> m. 07875 074 534
> t. 0208 352 1741
>

Thanks paul for you quick reply but I have to stick with qmail. I want
to check envelopes when user attempts to send message. Because our
company want to restrict some users to send message to selected
domains only. I've been given this task. Anyway thanks again for your
time.
--
Regards,
Hameed U. Khan
Registered Linux User #: 354374
-
*Computer without Linux is just like the world without computer.*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Console output

2005-10-05 Thread Johan Geldenhuys

This might help. Never used it though.

Johan


Christian Wyglendowski wrote:


> -Original Message-
 

From: [EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED] On Behalf Of Oliver Maunder

Sent: Wednesday, October 05, 2005 1:13 PM
To: tutor@python.org
Subject: [Tutor] Console output

Does anyone know how I can update a line of console output 
without creating a new line? 
   



Hi Oliver,

If you are on a *nix system, check out the "curses" package in the
standard library.  I have never used it, but it provides ways to
accomplish what you are after.

HTH,

Christian
http://www.dowski.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

 

class progressBar:
	def __init__(self, minValue = 0, maxValue = 10, totalWidth=12):
		self.progBar = "[]"   # This holds the progress bar string
		self.min = minValue
		self.max = maxValue
		self.span = maxValue - minValue
		self.width = totalWidth
		self.amount = 0   # When amount == max, we are 100% done 
		self.updateAmount(0)  # Build progress bar string

	def updateAmount(self, newAmount = 0):
		if newAmount < self.min: newAmount = self.min
		if newAmount > self.max: newAmount = self.max
		self.amount = newAmount

		# Figure out the new percent done, round to an integer
		diffFromMin = float(self.amount - self.min)
		percentDone = (diffFromMin / float(self.span)) * 100.0
		percentDone = round(percentDone)
		percentDone = int(percentDone)

		# Figure out how many hash bars the percentage should be
		allFull = self.width - 2
		numHashes = (percentDone / 100.0) * allFull
		numHashes = int(round(numHashes))

		# build a progress bar with hashes and spaces
		self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]"

		# figure out where to put the percentage, roughly centered
		percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) 
		percentString = str(percentDone) + "%"

		# slice the percentage into the bar
		self.progBar = self.progBar[0:percentPlace] + percentString + 
self.progBar[percentPlace+len(percentString):]

	def __str__(self):
		return str(self.progBar)

==

import time
prog = progressBar(0, 100, 77)
for i in xrange(101):
prog.updateAmount(i)
print prog, "\r",
time.sleep(.05)

==

# Best not to print it every iteration, Terry Carroll, 2004/01/26
#  It can be a substantial performance hit to print the bar every iteration, whether it changes or not. At 100 iterations, like Josiah's' example, it changes every iteration, so it won't' matter. But if you have more than a few thousand, it's' worth checking and not printing an unchanged bar: 
limit = 100

prog = progressBar(0, limit, 77)
oldprog = str(prog)
for i in xrange(limit+1):
prog.updateAmount(i)
if oldprog != str(prog):
print prog, "\r",
oldprog=str(prog)
print
=

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


Re: [Tutor] New Python book

2005-10-05 Thread Dick Moores
Andrew Fant wrote at 11:41 10/5/2005:
>Kent Johnson wrote:
> > Dick Moores wrote:
> >
> >>Magnus Lie Hetland's new book, _Beginning Python: From Novice to
> >>Professional_ was published by Apress on Sept. 26 (in the U.S.). Very
> >>much worth a look, IMHO. But what do the tutors think?
> >>
> >>
> >
> >
> > This seems to be an update to his previous book, "Practical Python", 
> rather than a completely new book. The TOC is almost identical. I 
> haven't read the earlier book, either, so I don't have an opinion. The 
> same sample chapter is available for each if anyone wants to compare. 
> (see www.apress.com)
> >
> > Kent
>
>Has he at least changed the GUI chapters away from AnyGUI to one of the 
>standard
>toolkits?  The last edition would have been more use to me if it didn't 
>do all
>of its GUI programming in a toolkit that the author has removed from 
>circulation.

No AnyGUI. Emphasis on wxPython.

Dick Moores

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


Re: [Tutor] Console output

2005-10-05 Thread Oliver Maunder
Just what I needed - thanks everyone. I never realised '\r' was actually good for something other than Windows line breaks!

Olly

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


Re: [Tutor] Console output

2005-10-05 Thread Alan Gauld
> 14% [===> ] 344,192 16.28K/s ETA 02:19
>
> All the figures and the progress bar get continously updated. The only way 
> I
> know of sending output to the console is to use print or 
> sys.stdout.write(),
> but that would give me:
> 14% [===> ] 344,192 16.28K/s ETA 02:19
> 18% [=> ] 344,192 16.28K/s ETA 02:19
> 20% [> ] 344,192 16.28K/s ETA 02:19

Usually thats done using curses which allows ypu to address the cursor on
the screen using coordinates. However for a single line you can fake it
using control codes for the specific terminal.

For example (as any vi user knows!) Ctrl J is line feed, Ctrl H is backspace
Ctrl G is beep(I think?), Ctrl U is delete to start of line, etc

You can use Ctrl H as a way of backspacing on the same line to the point
you want then inserying the updated text, or just use Ctrl U to delete the 
line
and rewrite it. You need to write to sys.stdout to do this properly and of
course don't ever write a newline until you are done!

HTH,

Alan G. 

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


[Tutor] Accessing Variables

2005-10-05 Thread Matt Williams
Dear List,

I'm trying to clarify something about accessing variables.

If I have ONE.py file with some variable a, and ONE imports TWO, which
has a variable b, can TWO access variable a (I don't think so, but I
just thought I'd check).

I guess the way round this is just to make some classes & objects, and
then they can easily pass parameters to each other, but I just thought
I'd check.

Matt  

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


Re: [Tutor] need help to understand terms for desinging a program

2005-10-05 Thread paul brian
I would suggest that you look firstly at qmails own built in ruleset.
something like that must be achieveable without writing a special plugin.

qmail control files are usually in /var/qmail/control. Nothing obvious
in the man pages i am afraid.

Good luck


On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote:
> On 10/5/05, paul brian <[EMAIL PROTECTED]> wrote:
> > This is a pretty big question, and it would be easier to answer if you
> > can give us more details about what you want to do.
> >
> > It seems you want to inspect outgoing mails (possibly rewrite their
> > addresses?) before the mails are sent out.
> >
> > If you are looking to send out emails to a list then I suggest looking
> > at mailman - a python mailing list manager.
> >
> > If you want to use python to examine mail messages and do not care
> > what mailserver (MTA) you use you could try exim instead of qmail and
> > then try exim-python.
> > http://botanicus.net/dw/exim-python/exim-4.32py1.html
> >
> >
> >
> >
> >
> > On 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]> wrote:
> > > Hi,
> > >  I need to make a program which will accomplish following. I dont
> > > need the code. I want to make it myself. But I need guidance from you
> > > people because I am not a good programmer. I need help in
> > > understanding following terms.
> > >
> > >   " qmail-queue  reads  a  mail message from descriptor 0.  It
> > >   then reads envelope information  from  descriptor  1.   It
> > >   places  the  message  into  the  outgoing queue for future
> > >   delivery by qmail-send.
> > >
> > >   The envelope information is  an  envelope  sender  address
> > >   followed  by  a list of envelope recipient addresses.  The
> > >   sender address is preceded by the letter F and  terminated
> > >   by  a  0  byte.  Each recipient address is preceded by the
> > >   letter T and terminated by a 0 byte.  The list of  recipi-
> > >   ent addresses is terminated by an extra 0 byte.  If qmail-
> > >   queue sees end-of-file before the extra 0 byte, it  aborts
> > >   without placing the message into the queue."
> > >
> > >  I want to inspect messages before passing them to actuall qmail-queue
> > > program.
> > > Thanks in advance for your help.
> > > --
> > > Regards,
> > > Hameed U. Khan
> > > Registered Linux User #: 354374
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> >
> >
> > --
> > --
> > Paul Brian
> > m. 07875 074 534
> > t. 0208 352 1741
> >
>
> Thanks paul for you quick reply but I have to stick with qmail. I want
> to check envelopes when user attempts to send message. Because our
> company want to restrict some users to send message to selected
> domains only. I've been given this task. Anyway thanks again for your
> time.
> --
> Regards,
> Hameed U. Khan
> Registered Linux User #: 354374
> -
> *Computer without Linux is just like the world without computer.*
>


--
--
Paul Brian
m. 07875 074 534
t. 0208 352 1741
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Handling Objects

2005-10-05 Thread Eric Walker
New to Python and trying to do some class stuff with a simple task. 
Problem:
1) get a list of file names in a directory
2) create variables with the same name of each filename pulled from the 
directory.
3) Create an object for each and pass into the __init__ method the stringname 
of the file name.

This way I get a collection of objects that are the same name as the file name 
and within each instance of the class , a particular attribute will have the 
string name of the object.  Hope this isn't too confusing.. example.


class TPROJ:
def __init__(self,value):#createMethod auto executes since it has __
self.BASENAME = value

   def display(self):#display method
print self.BASENAME

def getNames():
import os
currentDir=os.getcwd()
temp=currentDir + '/TEMP'
os.chdir(temp)
baseList=os.listdir(".")
for name in baseList:
name = TPROJ(name)
print name

Can anyone see what I am trying to do?

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


Re: [Tutor] Accessing Variables

2005-10-05 Thread Adam
What you can do is if ONE.py has a class with the variable a, in it,
you can pass the class instance (ie. self) and then you can call any
function or get any global class variable.
eg
def foo(parent):
    print parent.aOn 05/10/05, Matt Williams <[EMAIL PROTECTED]> wrote:
Dear List,I'm trying to clarify something about accessing variables.If I have 
ONE.py file with some variable a, and ONE imports TWO, whichhas a variable b, can TWO access variable a (I don't think so, but Ijust thought I'd check).I guess the way round this is just to make some classes & objects, and
then they can easily pass parameters to each other, but I just thoughtI'd check.Matt___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Accessing Variables

2005-10-05 Thread paul brian
Sort ofnot really

When a module is imported the following things happen

import ONE

a module object (dict essentially) named ONE is created. This is the
module ONE.py's namespace.
The module object is added to sys.modules
the code in the object is executed inside the ONE dict (namespace)

now if ONE has at the top
import os

ONE is able to use the line
os.path.join (mydir, "foo.txt")

If however we do not have the line import os we will get an error
as the namespace of one does not have a reference to the module object of os

as an example import your one.py and run

pprint.pprint(sys.modules['one'].__dict__)

You will see what a virgin namesapce looks like
- there is a lot in there but it boils down to
__builtins__, __doc__, __file__, __name__ and whatever you define (_-dict__)

care notes
---
You can easily get into circular references with imports, simply
because code at the module level (ie not in a function or class) will
be executed at the first import - and if it calls code that is in the
next module which waits on code in the first etc etc.

So as you said, put everything into classes or functions or be very
careful with your imports.

(I am not sure I answered the question but it is late now...:-)

yrs



On 10/5/05, Matt Williams <[EMAIL PROTECTED]> wrote:
> Dear List,
>
> I'm trying to clarify something about accessing variables.
>
> If I have ONE.py file with some variable a, and ONE imports TWO, which
> has a variable b, can TWO access variable a (I don't think so, but I
> just thought I'd check).
>
> I guess the way round this is just to make some classes & objects, and
> then they can easily pass parameters to each other, but I just thought
> I'd check.
>
> Matt
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
--
Paul Brian
m. 07875 074 534
t. 0208 352 1741
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Shell Not Saved Problem

2005-10-05 Thread Steve Haley








Dear folks,

 

Just wanted to thank everyone for the help.  I think I
know what was going on with that “The buffer for Python Shell is not
saved” message I was getting when I tried to run a script. 
Apparently you need to open the module before you run the script and also to
re-open it each time you want to run the script.  That seems a little
strange to me but it appears to work that way.  By the way, a couple of
folks said their screen didn’t look like what I described and wondered
what version I was using.  It is version 2.1 which I have because it that
version is bundled with ESRI ArcGIS 9 which I have.  I have been wondering
if I can update that version but am afraid that it might be customized to
ArcGIS somehow and I might mess that up if I upgrade just the Python portion.

 

Also, someone advised that the Shell
window not be used that way anyway.  I think I agree and will operate from
Pythonwin from now on.  A couple of folks also mentioned a book, Beginning
Python: From Novice to Professional.  I think I might try
that.

 

Again, thanks everyone for all the help.  I was very
impressed with the response to my cry for help.

 

- Steve






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


Re: [Tutor] Handling Objects

2005-10-05 Thread Kent Johnson
Eric Walker wrote:
> New to Python and trying to do some class stuff with a simple task. 
> Problem:
> 1) get a list of file names in a directory
> 2) create variables with the same name of each filename pulled from the 
> directory.
> 3) Create an object for each and pass into the __init__ method the stringname 
> of the file name.
> 
> This way I get a collection of objects that are the same name as the file 
> name 
> and within each instance of the class , a particular attribute will have the 
> string name of the object.  Hope this isn't too confusing.. example.

What will you do with the names and objects once you have them? A better 
approach is probably to keep a dictionary that maps names to objects. If your 
object is really just storing the name you might as well just keep a list of 
names - the object isn't adding any value. If the object is going to have more 
behaviour then use a dict. If you really just want to print the names then you 
don't need to store them at all. For example with a dict:

class TPROJ:
# as before

def getNames():
import os
currentDir=os.getcwd()
temp=currentDir + '/TEMP'
os.chdir(temp)
baseList=os.listdir(".")
nameDict = {}
for name in baseList:
nameDict[name] = TPROJ(name)
print name
return nameDict

HTH,
Kent
> 
> 
> class TPROJ:
> def __init__(self,value):#createMethod auto executes since it has __
> self.BASENAME = value
> 
>def display(self):#display method
> print self.BASENAME
> 
> def getNames():
> import os
> currentDir=os.getcwd()
> temp=currentDir + '/TEMP'
> os.chdir(temp)
> baseList=os.listdir(".")
> for name in baseList:
> name = TPROJ(name)
> print name
> 
> Can anyone see what I am trying to do?
> 
> Python Newbie...
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

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


Re: [Tutor] Accessing Variables

2005-10-05 Thread Kent Johnson
Matt Williams wrote:
> Dear List,
> 
> I'm trying to clarify something about accessing variables.
> 
> If I have ONE.py file with some variable a, and ONE imports TWO, which
> has a variable b, can TWO access variable a (I don't think so, but I
> just thought I'd check).

You are right. TWO can import ONE to get access to ONE.a but circular imports 
are usually a bad idea and can cause subtle bugs.
> 
> I guess the way round this is just to make some classes & objects, and
> then they can easily pass parameters to each other, but I just thought
> I'd check.

That is a good solution. An alternative is to make a module THREE that both ONE 
and TWO import.

Kent

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

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


Re: [Tutor] Handling Objects

2005-10-05 Thread Eric Walker
Well,
I think I probably can do this easier in perl but I took a vow I would try and 
learn python.  I know I am using classes here and really don't need objects. 
This is just another way for me to learn how to work with classes within 
python. My object actually will be storing like 5 or 6 different attributes 
but I didn't include them in the example.  These attributes  will be certain 
things that are read from the file.  Once I get the objects i want to create 
in another directory the same files with the same names but put different 
data into the new files depending on what I read from the original files.

Python Newbie


On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote:
> Eric Walker wrote:
> > New to Python and trying to do some class stuff with a simple task.
> > Problem:
> > 1) get a list of file names in a directory
> > 2) create variables with the same name of each filename pulled from the
> > directory.
> > 3) Create an object for each and pass into the __init__ method the
> > stringname of the file name.
> >
> > This way I get a collection of objects that are the same name as the file
> > name and within each instance of the class , a particular attribute will
> > have the string name of the object.  Hope this isn't too confusing..
> > example.
>
> What will you do with the names and objects once you have them? A better
> approach is probably to keep a dictionary that maps names to objects. If
> your object is really just storing the name you might as well just keep a
> list of names - the object isn't adding any value. If the object is going
> to have more behaviour then use a dict. If you really just want to print
> the names then you don't need to store them at all. For example with a
> dict:
>
> class TPROJ:
> # as before
>
> def getNames():
> import os
> currentDir=os.getcwd()
> temp=currentDir + '/TEMP'
> os.chdir(temp)
> baseList=os.listdir(".")
> nameDict = {}
> for name in baseList:
> nameDict[name] = TPROJ(name)
> print name
> return nameDict
>
> HTH,
> Kent
>
> > class TPROJ:
> > def __init__(self,value):#createMethod auto executes since it has __
> > self.BASENAME = value
> >
> >def display(self):#display method
> > print self.BASENAME
> >
> > def getNames():
> > import os
> > currentDir=os.getcwd()
> > temp=currentDir + '/TEMP'
> > os.chdir(temp)
> > baseList=os.listdir(".")
> > for name in baseList:
> > name = TPROJ(name)
> > print name
> >
> > Can anyone see what I am trying to do?
> >
> > Python Newbie...
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Eric Walker
EDA/CAD Engineer
Work: 208-368-2573
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Console output

2005-10-05 Thread Marcin Komorowski

- Original Message - 
From: "Roel Schroeven" <[EMAIL PROTECTED]>
To: 
Sent: Wednesday, October 05, 2005 2:53 PM
Subject: Re: [Tutor] Console output


> Oliver Maunder wrote:
>> Does anyone know how I can update a line of console output without
>> creating a new line? I'm not explaning this too well, so here's an 
>> example.
>>
>> When you download a file with wget, the console display looks like this:
>>
>> 14% [===>]
>> 344,192   16.28K/sETA 02:19
>>
>> All the figures and the progress bar get continously updated. The only
>> way I know of sending output to the console is to use print or
>> sys.stdout.write(), but that would give me:
>> 14% [===>]
>> 344,192   16.28K/sETA 02:19
>> 18% [=>   ]
>> 344,192   16.28K/sETA 02:19
>> 20% [>]
>> 344,192   16.28K/sETA 02:19
>>
>> ...and that's really not what I'm after!
>>
>> Any help and ideas would be appreciated
>
> You need to:
> - not write a newline
> - backup to the beginning of the line
>
> Simple example:
>
> import sys
> import time
>
> def progress(n):
>for i in range(n+1):
>sys.stdout.write('\r%3s%% [%s>%s]' % (i, '='*i, ' '*(n-i)))
>sys.stdout.flush()
>time.sleep(0.5)
>
> progress(60)
>

This works nicely, but do not forget that \r does not clear what you already 
have on the line, so you are safe if every time you re-write the line, you 
output the same number of characters, but if it is less, you will have 
residual from previous line.  The way around it is to output a line of 
spaces that overwrites the previous line.

> No newline is written, and the program backs up to the beginning of the
> line using carriage return, '\r'. You can also put the carriage return
> at the end of the line; the difference is that the cursor will be left
> at the beginning of the line instead of at the end.
>
> It's also possible to back up using backspaces ('\b'), but then you need
> to count how many characters you wrote and use the equal amount of
> backslashes.
>
> -- 
> If I have been able to see further, it was only because I stood
> on the shoulders of giants.  -- Isaac Newton
>
> Roel Schroeven
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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


Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]

2005-10-05 Thread Kent Johnson
Michael Cotherman wrote:
> def UnStuffData(src,dst,len):
> 
>for code in src:
>   for i in range(1,code):
>   dst.append(i)
> 
>   if code < 0xff
>   dst.append('\0') 
> 
> the above is the below code uncommented...
>  it(and the original code) just seem to find the end
> and puts a zero there...
> 
> I do not see the existing zeroes replaced. this is
> kinda why I wanted to start from the specification...

The above is the decoding code, it does what you describe below. It is adding 
the zeros back in, that is the dst.append('\0')

Kent

> decoding is:
> pop the first byte of the packet off and place
> subsequent bytes into the output until you get to the
> byte pointed to by the popped byte. When you reach
> that byte, read its value as the new 'relative'
> pointer, and copy x00 to the output. Proceed as above,
> placing bytes to the output until the relative pointer
> is reached or the end of the packet occurrs.
> 
> I guess I need to look if I wish for this part of the
> program to handle the input as one big existing
> string, or work on it a byte at a time as it comes in.
>  
> 
> -mike c

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


Re: [Tutor] Accessing Variables

2005-10-05 Thread Alan Gauld
> If I have ONE.py file with some variable a, and ONE imports TWO, which
> has a variable b, can TWO access variable a (I don't think so, but I
> just thought I'd check).

Correct you can't do it. And quite rightly so because trying to do so would
indicate a faulty design! When we import a module it can be one of two 
things:
1) A generic reusable bit of code written by someone else which has no
knowledge of the internal structure of our code, therefore it can never
   attempt to access our code.
2) A module that we have written as part of an overall solution. If that
module tries to access code in our module it means we have not factored
our code properly to produce reusable modules(in fact the moduile is
not modular!

Modules should only access their own data or the data in other modules
that they import, there should not be cyclic dependencies. If there are,
we have a faulty design.

> I guess the way round this is just to make some classes & objects, and
> then they can easily pass parameters to each other, but I just thought
> I'd check.

You can pass parameters between modules without resorting to classes,
thats an entirely different animal;

## ONE.py #

import TWO

onevar = TWO.twovar

TWO.init(onevar)
TWO.foo()

 TWO.py 

class UninitialisedModuleError(Exception)

twovar = 77
importer = None  #placeholder variable

def init(aValue):
global onevar
onevar = aValue

def foo():
   if onevar:
   print onevar
   else:
raise UninitialisedModuleError

#

So by using an init function TWO can grab a value from whatever
module imports TWO. If the module is not initialised an exception
gets raised. This mechanism provides a safe way to avoid circular
dependencies by keeping TWO ignorant of the innards of the
importing module.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] Python Shell Not Saved Problem

2005-10-05 Thread Alan Gauld
> Also, someone advised that the Shell window not be used that way anyway. 
> I
> think I agree and will operate from Pythonwin from now on.

The same applies in Pythonwin. You cannot run the interactive shell buffer
because Python will try to execute all the output from the commands - they
get executed as soon as you type them. You run programs from the text 
buffers
and the output appears in the shell window.

The typical way of working is:
- start the IDE(IDLE or Pythonwin)
- from the Shell buffer default window use File->Open(or New) to
  open a new code editor window
- from the new window use Run to execute the code in the current edit pane.
- look at the output in the shell window/pane

You don't need to close the window between runs just save the code and
rerun it.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


[Tutor] How to write this to a file?

2005-10-05 Thread Dick Moores
I have a script that writes it's output to a file. I also print the time with

print "Time was %.4g seconds" % (timeEnd - timeStart)

How could I also have the same output of the print expression, written to 
the file?

Thanks,

Dick Moores

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


Re: [Tutor] Handling Objects

2005-10-05 Thread Kent Johnson
Eric Walker wrote:
> Well,
> I think I probably can do this easier in perl but I took a vow I would try 
> and 
> learn python.  I know I am using classes here and really don't need objects. 
> This is just another way for me to learn how to work with classes within 
> python. My object actually will be storing like 5 or 6 different attributes 
> but I didn't include them in the example.  These attributes  will be certain 
> things that are read from the file.  Once I get the objects i want to create 
> in another directory the same files with the same names but put different 
> data into the new files depending on what I read from the original files.

OK, I would just make a list of the objects, since one of the attributes is the 
name you have everything you need in the object.

def getNames():
import os
currentDir=os.getcwd()
temp=currentDir + '/TEMP'
os.chdir(temp)
baseList=os.listdir(".")
data = []
for name in baseList:
data.append(TPROJ(name))
print name
return data

then to use the data something like
for datum in data:
f = open(datum.name, 'w')
#etc

Kent

> 
> Python Newbie
> 
> 
> On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote:
> 
>>Eric Walker wrote:
>>
>>>New to Python and trying to do some class stuff with a simple task.
>>>Problem:
>>>1) get a list of file names in a directory
>>>2) create variables with the same name of each filename pulled from the
>>>directory.
>>>3) Create an object for each and pass into the __init__ method the
>>>stringname of the file name.
>>>
>>>This way I get a collection of objects that are the same name as the file
>>>name and within each instance of the class , a particular attribute will
>>>have the string name of the object.  Hope this isn't too confusing..
>>>example.
>>
>>What will you do with the names and objects once you have them? A better
>>approach is probably to keep a dictionary that maps names to objects. If
>>your object is really just storing the name you might as well just keep a
>>list of names - the object isn't adding any value. If the object is going
>>to have more behaviour then use a dict. If you really just want to print
>>the names then you don't need to store them at all. For example with a
>>dict:
>>
>>class TPROJ:
>># as before
>>
>>def getNames():
>>import os
>>currentDir=os.getcwd()
>>temp=currentDir + '/TEMP'
>>os.chdir(temp)
>>baseList=os.listdir(".")
>>nameDict = {}
>>for name in baseList:
>>nameDict[name] = TPROJ(name)
>>print name
>>return nameDict
>>
>>HTH,
>>Kent
>>
>>
>>>class TPROJ:
>>>def __init__(self,value):#createMethod auto executes since it has __
>>>self.BASENAME = value
>>>
>>>   def display(self):#display method
>>>print self.BASENAME
>>>
>>>def getNames():
>>>import os
>>>currentDir=os.getcwd()
>>>temp=currentDir + '/TEMP'
>>>os.chdir(temp)
>>>baseList=os.listdir(".")
>>>for name in baseList:
>>>name = TPROJ(name)
>>>print name
>>>
>>>Can anyone see what I am trying to do?
>>>
>>>Python Newbie...
>>>___
>>>Tutor maillist  -  Tutor@python.org
>>>http://mail.python.org/mailman/listinfo/tutor
>>
>>___
>>Tutor maillist  -  Tutor@python.org
>>http://mail.python.org/mailman/listinfo/tutor
> 
> 

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


Re: [Tutor] Console output

2005-10-05 Thread Kent Johnson
Oliver Maunder wrote:
> Just what I needed - thanks everyone. I never realised '\r' was actually 
> good for something other than Windows line breaks!

Hmm, just have to say something about the old days when 'carriage return' and 
'line feed' really meant something :-)

Kent

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


Re: [Tutor] How to write this to a file?

2005-10-05 Thread Kent Johnson
Dick Moores wrote:
> I have a script that writes it's output to a file. I also print the time with
> 
> print "Time was %.4g seconds" % (timeEnd - timeStart)
> 
> How could I also have the same output of the print expression, written to 
> the file?

The formatting part of the print is just an expression with a string value, you 
can assign it to a variable and write it to your file. You might want to add a 
newline:

timeMsg = "Time was %.4g seconds\n" % (timeEnd - timeStart)
f.write(timeMsg)

If you have a lot of output that you want to put to the console and to a log 
file you might like to look at the logging module. A single line of logging can 
be written to multiple places by the module.

Kent

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


Re: [Tutor] Handling Objects

2005-10-05 Thread Kent Johnson
Eric Walker wrote:
> Thanks Kent.. I think that would work for what I am doing. So is it safe to 
> say that python doesn't do variable interpolation like perl..?

I think so, though I don't really speak perl. The closest approximation is the 
string formatting operation and the string.Template class.
http://docs.python.org/lib/typesseq-strings.html
http://docs.python.org/lib/node109.html

Kent

> 
> Thanks in advance.
> 
> Python Newbie...
> 
> 
> On Wednesday 05 October 2005 05:20 pm, Kent Johnson wrote:
> 
>>Eric Walker wrote:
>>
>>>Well,
>>>I think I probably can do this easier in perl but I took a vow I would
>>>try and learn python.  I know I am using classes here and really don't
>>>need objects. This is just another way for me to learn how to work with
>>>classes within python. My object actually will be storing like 5 or 6
>>>different attributes but I didn't include them in the example.  These
>>>attributes  will be certain things that are read from the file.  Once I
>>>get the objects i want to create in another directory the same files with
>>>the same names but put different data into the new files depending on
>>>what I read from the original files.
>>
>>OK, I would just make a list of the objects, since one of the attributes is
>>the name you have everything you need in the object.
>>
>>def getNames():
>>import os
>>currentDir=os.getcwd()
>>temp=currentDir + '/TEMP'
>>os.chdir(temp)
>>baseList=os.listdir(".")
>>data = []
>>for name in baseList:
>>data.append(TPROJ(name))
>>print name
>>return data
>>
>>then to use the data something like
>>for datum in data:
>>f = open(datum.name, 'w')
>>#etc
>>
>>Kent
>>
>>
>>>Python Newbie
>>>
>>>On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote:
>>>
Eric Walker wrote:

>New to Python and trying to do some class stuff with a simple task.
>Problem:
>1) get a list of file names in a directory
>2) create variables with the same name of each filename pulled from the
>directory.
>3) Create an object for each and pass into the __init__ method the
>stringname of the file name.
>
>This way I get a collection of objects that are the same name as the
>file name and within each instance of the class , a particular
>attribute will have the string name of the object.  Hope this isn't too
>confusing.. example.

What will you do with the names and objects once you have them? A better
approach is probably to keep a dictionary that maps names to objects. If
your object is really just storing the name you might as well just keep a
list of names - the object isn't adding any value. If the object is going
to have more behaviour then use a dict. If you really just want to print
the names then you don't need to store them at all. For example with a
dict:

class TPROJ:
   # as before

def getNames():
   import os
   currentDir=os.getcwd()
   temp=currentDir + '/TEMP'
   os.chdir(temp)
   baseList=os.listdir(".")
   nameDict = {}
   for name in baseList:
   nameDict[name] = TPROJ(name)
   print name
   return nameDict

HTH,
Kent


>class TPROJ:
>   def __init__(self,value):#createMethod auto executes since it has __
>   self.BASENAME = value
>
>  def display(self):#display method
>   print self.BASENAME
>
>def getNames():
>   import os
>   currentDir=os.getcwd()
>   temp=currentDir + '/TEMP'
>   os.chdir(temp)
>   baseList=os.listdir(".")
>   for name in baseList:
>   name = TPROJ(name)
>   print name
>
>Can anyone see what I am trying to do?
>
>Python Newbie...
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor

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

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


[Tutor] regExpress

2005-10-05 Thread Eric Walker
All,
If I have something like this:
import re
sample = 'myboss:isbad'
express = re.compile('(.*):(.*))
answer = re.match(express,sample)

how do I get it to  tell me if it was a match or not. I have tried 
answer.match . It just gives me an object pointer or something.

Thanks
Python Newbie...



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


Re: [Tutor] How to write this to a file?

2005-10-05 Thread Dick Moores
Kent Johnson wrote at 16:32 10/5/2005:
>Dick Moores wrote:
> > I have a script that writes it's output to a file. I also print the 
> time with
> >
> > print "Time was %.4g seconds" % (timeEnd - timeStart)
> >
> > How could I also have the same output of the print expression, 
> written to
> > the file?
>
>The formatting part of the print is just an expression with a string 
>value, you can assign it to a variable and write it to your file. You 
>might want to add a newline:
>
>timeMsg = "Time was %.4g seconds\n" % (timeEnd - timeStart)
>f.write(timeMsg)

Thanks, Kent, that works!

>If you have a lot of output that you want to put to the console and to a 
>log file you might like to look at the logging module. A single line of 
>logging can be written to multiple places by the module.

I'll check out the logging module.

Dick

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


Re: [Tutor] regExpress

2005-10-05 Thread Kent Johnson
Eric Walker wrote:
> All,
> If I have something like this:
> import re
> sample = 'myboss:isbad'
> express = re.compile('(.*):(.*))
> answer = re.match(express,sample)
> 
> how do I get it to  tell me if it was a match or not. I have tried 
> answer.match . It just gives me an object pointer or something.

re.match() will return None if there is no match, or a match object if it 
succeeds. And your syntax isn't quite right, if you compile the re then call 
match() directly on the compiled object. With re.match() you pass the re string 
as the first arg and you don't have to compile it. In either case, the methods 
of the match object give details of the match.
http://docs.python.org/lib/match-objects.html

Finally, you may want to use re.search() instead of match(); match will only 
match the re at the beginning of the string, kind of like if the re started 
with '^'.

 >>> import re
 >>> sample = 'myboss:isbad'
 >>> express = re.compile('(.*):(.*)')
 >>> answer = express.match(sample)
 >>> answer
<_sre.SRE_Match object at 0x008C4A40>
 >>> answer.groups()
('myboss', 'isbad')
 >>> answer = express.match('No colon here, move along')
 >>> answer
 >>> print answer
None

Kent

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


Re: [Tutor] Handling Objects

2005-10-05 Thread Eric Walker
Thanks Kent.. I think that would work for what I am doing. So is it safe to 
say that python doesn't do variable interpolation like perl..?

Thanks in advance.

Python Newbie...


On Wednesday 05 October 2005 05:20 pm, Kent Johnson wrote:
> Eric Walker wrote:
> > Well,
> > I think I probably can do this easier in perl but I took a vow I would
> > try and learn python.  I know I am using classes here and really don't
> > need objects. This is just another way for me to learn how to work with
> > classes within python. My object actually will be storing like 5 or 6
> > different attributes but I didn't include them in the example.  These
> > attributes  will be certain things that are read from the file.  Once I
> > get the objects i want to create in another directory the same files with
> > the same names but put different data into the new files depending on
> > what I read from the original files.
>
> OK, I would just make a list of the objects, since one of the attributes is
> the name you have everything you need in the object.
>
> def getNames():
> import os
> currentDir=os.getcwd()
> temp=currentDir + '/TEMP'
> os.chdir(temp)
> baseList=os.listdir(".")
> data = []
> for name in baseList:
> data.append(TPROJ(name))
> print name
> return data
>
> then to use the data something like
> for datum in data:
> f = open(datum.name, 'w')
> #etc
>
> Kent
>
> > Python Newbie
> >
> > On Wednesday 05 October 2005 04:29 pm, Kent Johnson wrote:
> >>Eric Walker wrote:
> >>>New to Python and trying to do some class stuff with a simple task.
> >>>Problem:
> >>>1) get a list of file names in a directory
> >>>2) create variables with the same name of each filename pulled from the
> >>>directory.
> >>>3) Create an object for each and pass into the __init__ method the
> >>>stringname of the file name.
> >>>
> >>>This way I get a collection of objects that are the same name as the
> >>> file name and within each instance of the class , a particular
> >>> attribute will have the string name of the object.  Hope this isn't too
> >>> confusing.. example.
> >>
> >>What will you do with the names and objects once you have them? A better
> >>approach is probably to keep a dictionary that maps names to objects. If
> >>your object is really just storing the name you might as well just keep a
> >>list of names - the object isn't adding any value. If the object is going
> >>to have more behaviour then use a dict. If you really just want to print
> >>the names then you don't need to store them at all. For example with a
> >>dict:
> >>
> >>class TPROJ:
> >># as before
> >>
> >>def getNames():
> >>import os
> >>currentDir=os.getcwd()
> >>temp=currentDir + '/TEMP'
> >>os.chdir(temp)
> >>baseList=os.listdir(".")
> >>nameDict = {}
> >>for name in baseList:
> >>nameDict[name] = TPROJ(name)
> >>print name
> >>return nameDict
> >>
> >>HTH,
> >>Kent
> >>
> >>>class TPROJ:
> >>>def __init__(self,value):#createMethod auto executes since it has __
> >>>self.BASENAME = value
> >>>
> >>>   def display(self):#display method
> >>>print self.BASENAME
> >>>
> >>>def getNames():
> >>>import os
> >>>currentDir=os.getcwd()
> >>>temp=currentDir + '/TEMP'
> >>>os.chdir(temp)
> >>>baseList=os.listdir(".")
> >>>for name in baseList:
> >>>name = TPROJ(name)
> >>>print name
> >>>
> >>>Can anyone see what I am trying to do?
> >>>
> >>>Python Newbie...
> >>>___
> >>>Tutor maillist  -  Tutor@python.org
> >>>http://mail.python.org/mailman/listinfo/tutor
> >>
> >>___
> >>Tutor maillist  -  Tutor@python.org
> >>http://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Eric Walker
EDA/CAD Engineer
Work: 208-368-2573
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Getting name scope

2005-10-05 Thread Bernard Lebel
Hello,

Anyone know if it is possible to find out in what scope lies a name?
For instance, let say I'm using a name in a function, but the name is
actually in the global scope. I would like to know if this name was
found in what scope. Is it possible at all?


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


Re: [Tutor] Embedding

2005-10-05 Thread Kent Johnson
You might be interested in this article about making a game in a week using 
Python and Pygame:
http://www.gamedev.net/reference/articles/article2259.asp

Joseph Quigley wrote:
> Hi,
> Ok, I'll try to convince them to try python... but still, would it be 
> best to just:
> Program in C with Python and Java scripts
> Program in Python with a little bit of C?
> 
> The game we're trying to make is a Super Mario type game (or super tux 
> for you like linux games).
> I suppose pygame would make it a breeze for video, sound and graphics!  
> My only problem is I haven't done any games withy pygame at all and 
> can't find any pygame tutorials (when I google).
> Thanks,
>   Joe
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

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


Re: [Tutor] Getting name scope

2005-10-05 Thread Kent Johnson
Bernard Lebel wrote:
> Hello,
> 
> Anyone know if it is possible to find out in what scope lies a name?
> For instance, let say I'm using a name in a function, but the name is
> actually in the global scope. I would like to know if this name was
> found in what scope. Is it possible at all?

Look for the name in locals() and globals()? But why do you care?

 >>> a=1
 >>> def scopeOf(name):
 ...   x=3
 ...   if name in locals():
 ... print name, 'is local'
 ...   elif name in globals():
 ... print name, 'is global'
 ...   else:
 ... print 'I don\'t know about', name
 ...
 >>> scopeOf('x')
x is local
 >>> scopeOf('a')
a is global
 >>> scopeOf('foo')
I don't know about foo

This assumes that you actually know the name as a string. If you are trying to 
find out something about the variable in the calling scope then it is harder. 
There are hacks to find out the name of the variable in the calling scope but 
why?

Kent

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


Re: [Tutor] Getting name scope

2005-10-05 Thread Bernard Lebel
Thanks for the answer.

I have to confess this question is driven only by curiosity, I was not
even hoping to get such a function. I was reading some stuff about the
scopes in JScript and somehow this question arose in my mind.

For the record, the tutorial I am watching said that a name exists
*only* inside a block, wich is a local scope itself. So that statement
defied my experience with JScript so I wanted to put it to the test:

(this is JScript code ran into a 3D application that embeds Python,
JScript and few other activeX-capable langages).


var oSel = selection(0);

if ( oSel.type == 'polymsh' )
{
var oMesh = oSel;
}

logmessage( oMesh.name );

//Output
//INFO : sphere



Then I was curious if it would have been the same in Python (I knew it
was not, but tested it nonetheless):

oSel = Application.selection(0)

if oSel.type == 'polymsh': oMesh = oSel

Application.logmessage( oMesh.name )

#Output
#INFO : sphere



So then the question arised if it was possible in Python to know to
what scope a name belongs. I don't know any use for this, but I just
wanted to know it was possible.


Thanks!
Bernard




On 10/5/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > Anyone know if it is possible to find out in what scope lies a name?
> > For instance, let say I'm using a name in a function, but the name is
> > actually in the global scope. I would like to know if this name was
> > found in what scope. Is it possible at all?
>
> Look for the name in locals() and globals()? But why do you care?
>
>  >>> a=1
>  >>> def scopeOf(name):
>  ...   x=3
>  ...   if name in locals():
>  ... print name, 'is local'
>  ...   elif name in globals():
>  ... print name, 'is global'
>  ...   else:
>  ... print 'I don\'t know about', name
>  ...
>  >>> scopeOf('x')
> x is local
>  >>> scopeOf('a')
> a is global
>  >>> scopeOf('foo')
> I don't know about foo
>
> This assumes that you actually know the name as a string. If you are trying 
> to find out something about the variable in the calling scope then it is 
> harder. There are hacks to find out the name of the variable in the calling 
> scope but why?
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regExpress

2005-10-05 Thread Eric Walker
Thanks so much Kent..

Eric ...

--- Kent Johnson <[EMAIL PROTECTED]> wrote:

> Eric Walker wrote:
> > All,
> > If I have something like this:
> > import re
> > sample = 'myboss:isbad'
> > express = re.compile('(.*):(.*))
> > answer = re.match(express,sample)
> > 
> > how do I get it to  tell me if it was a match or
> not. I have tried 
> > answer.match . It just gives me an object pointer
> or something.
> 
> re.match() will return None if there is no match, or
> a match object if it succeeds. And your syntax isn't
> quite right, if you compile the re then call match()
> directly on the compiled object. With re.match() you
> pass the re string as the first arg and you don't
> have to compile it. In either case, the methods of
> the match object give details of the match.
> http://docs.python.org/lib/match-objects.html
> 
> Finally, you may want to use re.search() instead of
> match(); match will only match the re at the
> beginning of the string, kind of like if the re
> started with '^'.
> 
>  >>> import re
>  >>> sample = 'myboss:isbad'
>  >>> express = re.compile('(.*):(.*)')
>  >>> answer = express.match(sample)
>  >>> answer
> <_sre.SRE_Match object at 0x008C4A40>
>  >>> answer.groups()
> ('myboss', 'isbad')
>  >>> answer = express.match('No colon here, move
> along')
>  >>> answer
>  >>> print answer
> None
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




__ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Handling Objects

2005-10-05 Thread Andrew P
To do:

$color = "Green";
print "$color apple.\n";

You would want:

color = "Green"
print "%s apple." % color

Both of which would print "Green apple."  That is actually
something I like about Perl, but it reinforces some bad habits, at
least for me.  Boilerplate coding, as it were, when doing quick
and dirty web stuff, which always ends up growing!  That and
inline regex will probably be the hardest thing to get used to.  

Good luck with Python, but you really won't need it.  I wrote a
script in Perl today to show a friend how to do something, and it
reinforced the amazing amount of -stuff- you need to remember to use
Perl, and the mind-draining way you can't type without thinking about
which way you will type it.   I swear it scares people away
from other languages for life :)

Python will be much, much easier to learn.  And hopefully you'll
spend more time typing what you want, than deciding how you should type
it, while doing the exact same things you always did.On 10/5/05, Eric Walker <[EMAIL PROTECTED]> wrote:
Thanks Kent.. I think that would work for what I am doing. So is it safe tosay that python doesn't do variable interpolation like perl..?
Thanks in advance.Python Newbie...

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


[Tutor] still not getting 'it'

2005-10-05 Thread Rosalee Dubberly
I am having problems with changing the parameters in my second function. I 
want the second function to run the same as the first, but take different
parameters. What am I doing wrong

def firstpart():
   """Define a function that takes no parameters and does the following:
   Returns (not prints) a list of 512 items, each consisting of the 
string, 'passed',
   unless the index of the item is a multiple of 3, 7, or 11,
   in which case the string for that index is 'tryagain'"""
   for n in range( 0, 55 ):
   if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
print 'passed,',
   else:
print 'tryagain,',
   return firstpart




def changes(passed=success,  tryagain=fail):
"""Define a second function that acts in the same way as the first 
function,
   except that it takes parameters whose values replace 'passed' and 
'tryagain' in the first function."""

for n in range ( 0, 55 ):
if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
print ' passed,',
else:
print 'tryagain,',

alist.append(['success', 'fail'])
return alist

thelist = changes('success', 'fail')

_
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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