Re: [Tutor] generating independent random numbers

2010-09-29 Thread Ewald Ertl
Hi,

On Wed, Sep 29, 2010 at 11:42 AM, Peter Otten <__pete...@web.de> wrote:

> Carter Danforth wrote:
>
> > Thanks for the replies, Dave and Joel. The reason I'm not just using the
> > time or datetime modules for a random date is because it's restricted to
> > 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
>
> The datetime module is not restricted to 1970...2038. It allows years
> 1... (it uses the Gregorian calendar even before its adoption).
>
> >>> import datetime
> >>> datetime.MINYEAR, datetime.MAXYEAR
> (1, )
> >>> datetime.date(1500, 2, 29)
> Traceback (most recent call last):
>  File "", line 1, in 
> ValueError: day is out of range for month
> >>> datetime.date(1600, 2, 29)
> datetime.date(1600, 2, 29)
>
> Just an attempt from my side:
The year 1500 didn't have a 29th of February, the 28th work for me but 29th
also fails here.
>>> datetime.date( 1500, 2, 28 )
datetime.date(1500, 2, 28)
>>> datetime.date( 1500, 2, 29 )
Traceback (most recent call last):
  File "", line 1, in 
ValueError: day is out of range for month


HTH
Ewald
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] O.T.

2004-12-30 Thread Ewald Ertl
Hi!

I#m 33, married, 2 Children ( 9 months old girl & 3 year old boy ). 
We are living in the south of Burgenland in Austria. My mother tounge is
german. 

I attended a secondary technical school studed electronics. After school 
I started working for a big company creating a power system control system 
delivering all over the world. There I had my first contact to SunOS/Unix. 

Now I work for a small company delivering software for the financial sector. 

I'm using SunRay's in work. 

programming languages: C/C++, a little bit java, ksh 
and very long ago asm, Turbo Pascal, fortran, perl

I'm doing Sys-Admin, network-admin, mail-admin and also development in our 
own middle-ware, providing the access to corebanking-system and other low-level 
technical connections and functions. 

Wish you all a happy new year

Ewald 

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


Re: [Tutor] Selecting text

2005-01-19 Thread Ewald Ertl
Hi kumar

If I unterstood your question correctly, you have to iterate over the refseq 
until 
you get the next entry, which starts with a '>'

on Tue, 18 Jan 2005 20:12:32 -0800 (PST)  kumar s <[EMAIL PROTECTED]> wrote :
-


kumar s > I could not think of any smart way to do this,
kumar s > although I have tried like this:
kumar s > 
kumar s > >>> for ele1 in Lseq:
kumar s >   for ele2 in refseq:
kumar s >   if ele1 in ele2:
kumar s >   k = ele2
kumar s >   s = refseq[ele2].startswith('>')

Here you index the list with an element, but the index must be an integer

kumar s >   print k,s
kumar s > 
kumar s >   
kumar s > 
kumar s > Traceback (most recent call last):
kumar s >   File "", line 5, in -toplevel-
kumar s > s = refseq[ele2].startswith('>')
kumar s > TypeError: list indices must be integers
kumar s > 
kumar s > 
kumar s > I do not know how to dictate to python to select lines
kumar s > between two > symbols. 
kumar s > 


--- end --
Perhaps this is a possible solution: 

Iteration of Lseq an then looping over all elements in refseq. 
if an element of refseq contains the ele1 the list-entry is printed. 
The nested while-loop print's the refseq -elements as long as the element
does not start with a '>'

for ele1 in Lseq:
i=0
while i < len(refseq):
if ele1 in refseq[i]:
print refseq[i]
i +=1
while not refseq[i].startswith('>'):
print refseq[i]
i+=1 # increment until the next entry starting 
with '>' is found
i +=1 # if search should continue if another element is present

HTH Ewald



-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] how to separate hexadecimal

2005-02-02 Thread Ewald Ertl
Hi!

Using binary operations: 

>>> a='0x87BE'
>>> str(hex(int(a,16) & 0xFF))
'0xbe'
>>> str(hex((int(a,16) & 0xFF00) / 0xFF))
'0x87'
>>> 

HTH Ewald 

on Wed, 2 Feb 2005 15:10:36 +0800  jrlen balane <[EMAIL PROTECTED]> wrote :
-

jrlen balane > i have a 4 digit hex number (2 bytes) and i want to separate it 
into 2
jrlen balane > digit hex (1 byte each) meaning i want to get the upper byte and 
the
jrlen balane > lower byte since i am going to add this two.
jrlen balane > how am i going to do this?
jrlen balane > should i treat it just like a normal string?
jrlen balane > please help, thanks.
jrlen balane > 
jrlen balane > ex. hexa = '0x87BE"  # what i want to do is:
jrlen balane >   a = 0x87, b = 0xBE# so that i could do this:
jrlen balane >   c = a + b#which should be equal to 0x145
jrlen balane > ___
jrlen balane > Tutor maillist  -  Tutor@python.org
jrlen balane > http://mail.python.org/mailman/listinfo/tutor
jrlen balane > 


--- end --

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


Re: [Tutor] Hex to Str

2005-02-04 Thread Ewald Ertl
Hello Heiko, 

I do not really know what you like to get, but the hex-number's in Python are 
usedd
in a numeric representation. As far as I have seen in the interpreter, this 
depends 
on the value:

>>> a=0xabccddd
>>> type(a)


>>> a=0xaabb
>>> type(a)


If you like to see the number as a hex-String you can use 
>>> hex(a)
'0xaabb'
the representation as an octal number
>>> oct(a)
'0125273'

HTH Ewald 

on Fri, 4 Feb 2005 14:18:28 +0100  "Tamm, Heiko" <[EMAIL PROTECTED]> wrote :
-

Tamm, Heiko > Hello,
Tamm, Heiko >  
Tamm, Heiko > I like to know, if it's possible to convert a Hex number into 
String or
Tamm, Heiko > other formats?
Tamm, Heiko >  
Tamm, Heiko > How can it be done?
Tamm, Heiko >  
Tamm, Heiko >  
Tamm, Heiko > Kind regards
Tamm, Heiko >  
Tamm, Heiko >   Heiko


--- end --

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


Re: [Tutor] Saving Entry fields in Tkinter

2005-03-01 Thread Ewald Ertl
Hi!

Perhaps this could help you: 

fileContent=open( "my/file/to/read", "r").readlines()

for line in fileContent:
print line.strip()   # remove leading and trailing whitspace's incl. \n


In the loop you could perhaps populate the entry-widgets. 

HTH  

Ewald 

on Tue, 1 Mar 2005 09:22:06 +  Adam Cripps <[EMAIL PROTECTED]> wrote :
-

Adam Cripps > I'm writing an application which has rows of Entry fields 
(created in
Adam Cripps > a loop - see previous thread; and thanks guys!). All the content 
of
Adam Cripps > the Entry fields are accessed through self.contentlist[i].get()
Adam Cripps > 
Adam Cripps > Now I'm trying to save the content of those fields in a friendly
Adam Cripps > format. I've used pickle in the past, but experienced problems 
with
Adam Cripps > pickling Tkinter widgets.
Adam Cripps > 
Adam Cripps > I'm saving using this method :- 
Adam Cripps > 
Adam Cripps > for i in self.contentlist:
Adam Cripps > saving = i.get() + "\n"
Adam Cripps > f.write(saving)
Adam Cripps > f.close()
Adam Cripps > 
Adam Cripps > which creates a text file with each entry field separated with a 
"\n". 
Adam Cripps > 
Adam Cripps > What would be a good way to open this file and re-populate the 
entry
Adam Cripps > fields with the content?  I'm not sure how to parse the text 
according
Adam Cripps > to the \n separator.
Adam Cripps > 
Adam Cripps > Am I going down the right path here? 
Adam Cripps > 
Adam Cripps > TIA
Adam Cripps > Adam


--- end --


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] Saving Entry fields in Tkinter

2005-03-01 Thread Ewald Ertl
Hi
 on Tue, 1 Mar 2005 15:31:10 +  Adam Cripps <[EMAIL PROTECTED]> wrote :
 
-
 Adam Cripps > > 
 Adam Cripps > Thanks Ewald - this is what I have so far, with a far from 
perfect result:
 Adam Cripps > File=open( FileName, "r")
 Adam Cripps > readlines = File.readlines()
 Adam Cripps > intcount = 0
 Adam Cripps > newcontent  =[]
 Adam Cripps > for line in readlines:
 Adam Cripps > print line.strip()   # remove leading and trailing 
whitspace's incl. \n
 Adam Cripps > self.contentlist[intcount].set(repr(line.strip))

 I think, here's the call missing  

self.contentlist[intcount].set(repr(line.strip()))
  ^^
 That should be the reason, why you get the reference to the method of the 
string 
 and not the content. 

 If your printing line.strip without the paranthesis you get the reference of 
the method. 
 This reference can be assigned to a variable to call it later. 


 Adam Cripps > intcount = intcount + 1
 Adam Cripps > 
 Adam Cripps > But all the entry fields are filled with these and not the text:
 Adam Cripps > 
 Adam Cripps > 
 Adam Cripps > 
 Adam Cripps > I'm not sure what else to do here...
 Adam Cripps > 
 Adam Cripps > any ideas?
 Adam Cripps > 
 Adam Cripps > Thanks
 Adam Cripps > Adam
 Adam Cripps >  --
 Adam Cripps >  http://www.monkeez.org
 Adam Cripps >  PGP key: 0x7111B833
 Adam Cripps > ___
 Adam Cripps > Tutor maillist  -  Tutor@python.org
 Adam Cripps > http://mail.python.org/mailman/listinfo/tutor
 Adam Cripps > 


 --- end --

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


Re: [Tutor] Paradox database files

2005-03-08 Thread Ewald Ertl
Hi Victor

on Tue, 08 Mar 2005 10:06:50 -0600  Victor Bouffier <[EMAIL PROTECTED]> wrote :
-

Victor Bouffier > Hi all,
Victor Bouffier > I know this is OT from Python, but does anybody know how to 
fix my 
Victor Bouffier > library issues. I get some awkward dependencies issues from 
these pylib 
Victor Bouffier > libraries.
Victor Bouffier > 
Victor Bouffier > # rpm -Uvh pxlib-0.4.3-1.i386.rpm
Victor Bouffier > error: Failed dependencies:
Victor Bouffier > libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386
Victor Bouffier > 
Victor Bouffier > but when I look into my libraries I find the necessary ones 
under /usr/lib:
Victor Bouffier > 
Victor Bouffier > # ll /usr/lib/libbz2*
Victor Bouffier > -rwxr-xr-x  1 root root 67594 Jun 15  2004 /usr/lib/libbz2.a
Victor Bouffier > lrwxrwxrwx  1 root root11 Feb  6 11:02 /usr/lib/libbz2.so 
-> libbz2.so.1
Victor Bouffier > lrwxrwxrwx  1 root root15 Feb  6 10:10 
/usr/lib/libbz2.so.1 -> 
Victor Bouffier > libbz2.so.1.0.2
Victor Bouffier > lrwxrwxrwx  1 root root24 Mar  8 09:41 
/usr/lib/libbz2.so.1.0 -> 
Victor Bouffier > /usr/lib/libbz2.so.1.0.2
Victor Bouffier > -rwxr-xr-x  1 root root 71724 Jun 15  2004 
/usr/lib/libbz2.so.1.0.2
Victor Bouffier > 

Perhap's there is a problem with the RPM-Database. I don't know how rpm works 
internaly, but it 
controls somewhere in a "database", which packages are installed on the system. 

On an old SuSE-System I can search, to which package a file belongs

rpm -q -f /usr/lib/libbz2.so
bzip2-1.0.2-103

Here I see, that libbz2.so belongs to the bzip2-Package. 
The other way is to list the files belonging to a package: 

rpm -q -l bzip2-1.0.2-103
/usr/bin/bunzip2
/usr/bin/bzcat
/usr/bin/bzip2
/usr/bin/bzip2recover
/usr/include/bzlib.h
/usr/lib/libbz2.a
/usr/lib/libbz2.la
/usr/lib/libbz2.so
/usr/lib/libbz2.so.1
/usr/lib/libbz2.so.1.0.0

During the installation/update-Process, I think, rpm looks up, all dependencys 
mentioned 
in the rpm if they are installed on the system via the "database" where it 
logs, 
what is installed. 

Try if you can get a package to which your /usr/lib/libbz2.so.1 belongs. 

The other way is, to install the rpm-Package without depdency-check's, but this 
could result in the availability of the pxlib-Package, but it perhaps does not 
work. 
You've to test this, before you keep the package.

"rpm -Uvh --nodeps"

This should ignore the dependencies and install the package. 



--- end --
HTH Ewald

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


Re: [Tutor] getting a webpage via python

2005-03-08 Thread Ewald Ertl
Hi Paul!

As mentioned earlier by Kent in this group under the subject:

Subject: Re: [Tutor] Downloading from http

Mark Kels wrote:
 > On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. <[EMAIL PROTECTED]> wrote:
 > 
 >>urllib or urllib2 or maybe httplib maybe?
 >>
 >>urlopen( url[, data])
 > I'm sorry, but I didn't understood a thing (maybe its because of my
 > bad english, and mybe its because I'm just dumb :). Anyway, can you
 > give me a code example or a link to a tutorial that talks about this ?

   >>> from urllib import urlopen
   >>> u=urlopen('http://www.google.com')
   >>> d=u.read()
   >>> print d[:200]
 Google

Re: [Tutor] big numbers

2005-03-15 Thread Ewald Ertl
Hi!

As far as I can remember, there was a change between some version's of python 
of 2.x.
Now there is an automatic conversion from int to long, when it is necessary. 

Regards, Ewald

on Tue, 15 Mar 2005 15:06:06 +0800  Robert Storey <[EMAIL PROTECTED]> wrote :
-

Robert Storey > Dear all,
Robert Storey > 
Robert Storey > I'm new to Python, and using Sam's Teach Yourself Python in 24 
Hours.
Robert Storey > The book introduces big numbers, saying that I should expect the
Robert Storey > following problem:
Robert Storey > 
Robert Storey > >>> 1 + 99
Robert Storey > OverflowError: integer literal too large
Robert Storey > 
Robert Storey > The "problem" is that this doesn't happen. When I execute this 
command,
Robert Storey > Python seems to automatically convert the result into a big 
number:
Robert Storey > 
Robert Storey > >>> 1 + 99
Robert Storey > 100L
Robert Storey > 
Robert Storey > This book is a few years old and was written for Python version 
1.5, and
Robert Storey > of course I'm using version 2.3, so I'm just wondering if this 
whole
Robert Storey > issue of big numbers is now being handled automatically?
Robert Storey > 
Robert Storey > This is my first post - sorry to be asking such a basic 
question.
Robert Storey > 
Robert Storey > TIA,
Robert Storey > Robert
Robert Storey > ___
Robert Storey > Tutor maillist  -  Tutor@python.org
Robert Storey > http://mail.python.org/mailman/listinfo/tutor
Robert Storey > 


--- end --


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] FTP retrieve

2005-03-15 Thread Ewald Ertl
Hi!

Looking up the ftplib-Module on my Solaris-Box

>>> print sys.version
2.3.3 (#1, Mar 10 2004, 06:25:19) 
[GCC 3.3.2]


I get the following doc for retrlines of the FTP-class: 

>>> print myFTP.retrlines.__doc__
Retrieve data in line mode.
The argument is a RETR or LIST command.
The callback function (2nd argument) is called for each line,
with trailing CRLF stripped.  This creates a new port for you.
print_line() is the default callback.


Here is stated, that CRLF is stripped for each line. 

I've done something similar and opended the targetfile in "binary"-mode.
'wb' instead of 'w', so that there will be no conversion of data during the 
write. 

The data is retrieved with the following command: 

myFTP.retrbinary( "RETR " + dat, open( dat, "wb" ).write )

Ewald

on Tue, 15 Mar 2005 15:30:39 +0100 (CET)  Øyvind <[EMAIL PROTECTED]> wrote :
-

Øyvind > I have opened an FTP connection, and use the following to download a 
logfile:
Øyvind > 
Øyvind > f = open('c:///web.log','w')
Øyvind > ftp.retrlines('RETR ex050202.log', f.write)
Øyvind > 
Øyvind > I have also tried with f.writelines.
Øyvind > 
Øyvind > It works, but not as well as I would like. All the \n's are removed. 
How
Øyvind > can I download an exact copy, so that each line actually ends up being 
on
Øyvind > a separate line?
Øyvind > 
Øyvind > Thanks in advance...
Øyvind > 
Øyvind > 
Øyvind > 


--- end --


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


[Tutor] Number of socketdescriptors > 250 and open() failed with to many open files

2005-03-31 Thread Ewald Ertl
Hi!

In a class derived from thread I open a socket-Connection to a remote 
Server. 
Here I start about 500 Thread's on a solaris-System. Sofar there is no 
problem, when the filedescriptorlimit is set high enough with ulimit -n. 

My Problem is, when a function in the class tries to open a regular file 
in the filesystem. Because of some limitations of the FILE-Structure ( in C ) 
it's not possible to open more files than  255. I think, that this is the 
problem 
here in python, when open() delivers "too many open files". 

In my C-Daemon I duplicated the socket-descriptors with fcntl to start after a 
offset with e.g. fcntl( socket, F_DUP, 100 ). 
And after this I use the new descriptor and close the old one. So there are 
everytime 
some descriptors below 255 ready for opening regular files. 

I tried the same thing in python. socket.fileno() delivers the descriptor of the
opened socket.  
The fcntl-Call in the module fcntl does also succeed. But after this I need 
a socket-Object for working on with the new filedescriptor. 
Constructing a new socket-Object with socket.fromfd() does not work, because 
this takes a new descriptor at the same low offset. 

Is there any possibility to get a socket-Object which uses the allready 
obtained 
filedescriptor from fcntl()? 


Thanks 

Ewald 

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


Re: [Tutor] function loading a file's lines to a list

2005-04-01 Thread Ewald Ertl
Hi!

on Fri, 01 Apr 2005 12:01:02 +0200  Adriano Varoli Piazza <[EMAIL PROTECTED]> 
wrote :
-

Adriano Varoli Piazza > 
Adriano Varoli Piazza > def loadfromfile(fname):
Adriano Varoli Piazza > try:
Adriano Varoli Piazza > finput = file(fname, 'r')
Adriano Varoli Piazza > global lines

global say, that lines is "global" defined. Otherwise as in your first 
version the lines-List is defined local in the loadfromfile()-function. 
(You can return the local list and assign it, where you call the loadfromfile()-
function. )

Adriano Varoli Piazza > lines = []
Adriano Varoli Piazza > for line in finput:
Adriano Varoli Piazza > line = line[:-1]
Adriano Varoli Piazza > lines.append(line)
Adriano Varoli Piazza > finput.close()
Adriano Varoli Piazza > #return lines

As you do not use the returned value of loadfromfile(), it's useless here.

Adriano Varoli Piazza > except:
Adriano Varoli Piazza > print "Couldn't load from file %s" % (fname)
Adriano Varoli Piazza > 
Adriano Varoli Piazza > works (with or without the return lines statements, 
that's why I
Adriano Varoli Piazza > commented it), but I don't understand why. I know lists 
are modified in-
Adriano Varoli Piazza > place, so I'd imagine it would work in the first case 
too.
Adriano Varoli Piazza > 

--- end --

HTH Ewald

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


Re: [Tutor] (no subject)

2005-04-14 Thread Ewald Ertl
Hi Jim, 

on Thu, 14 Apr 2005 01:09:14 -0500  "Jim and Laura Ahl" <[EMAIL PROTECTED]> 
wrote :
-

Jim and Laura Ahl > How come when I ask it to print i[2:4] from an inputted 
string it gives me the letters between two and four
Jim and Laura Ahl > 
Jim and Laura Ahl > But when I ask it to print i[-1:-4] it does not print 
anything.

Here you extract a slice starting with the last entry in i and ending much 
earlier, 
so you are asking for a slice with a negative length. 

Perhaps what you like is print i[-4:-1] ? 

--- end --
HTH Ewald 

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


Re: [Tutor] for loop

2005-04-19 Thread Ewald Ertl
Hi, 

I've slightly modified the for-Loop  containing the "else" and not the if: 

>>> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>>> for num in x:
... if 5 in num:
... break
... else:
... print "YES"
... 
>>>

second test: 

>>> x = [[1,2,3],[2,4,6],[8,4,6],[9,8,7]]
>>> for num in x:
... if 5 in num:
... break 
... else:
... print "YES"
... 
YES
>>> 

The else-Part is only executed, when the for ( or while) - loop is left 
regularly, without 
a break-statement. 

HTH Ewald 

on Tue, 19 Apr 2005 11:51:39 +0800  Ching-Yi Chan <[EMAIL PROTECTED]> wrote :
-

Ching-Yi Chan > *Ron A*  /Wed Jan  7 18:41:15 EST 2004/
Ching-Yi Chan > 
Ching-Yi Chan > I'm experimenting and would like 'yes' to be printed only if 5 
is not in
Ching-Yi Chan > the list, but I want to look in each list. This prints out two 
yeses.
Ching-Yi Chan > How do I get it to print just one 'yes'?
Ching-Yi Chan > 
Ching-Yi Chan > x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
Ching-Yi Chan > 
Ching-Yi Chan > for num in x:
Ching-Yi Chan > if 5 in num:
Ching-Yi Chan > break
Ching-Yi Chan > else:
Ching-Yi Chan > print 'yes'  
Ching-Yi Chan > 
Ching-Yi Chan > 
--
Ching-Yi Chan > 
Ching-Yi Chan > Hi, I read the code and consider for a while, you can try it :
Ching-Yi Chan > 
Ching-Yi Chan > x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
Ching-Yi Chan > print [ e for e in x if 5 in e]
Ching-Yi Chan > 
Ching-Yi Chan > 
Ching-Yi Chan > ___
Ching-Yi Chan > Tutor maillist  -  Tutor@python.org
Ching-Yi Chan > http://mail.python.org/mailman/listinfo/tutor
Ching-Yi Chan > 


--- end --

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


Re: [Tutor] input()

2005-04-29 Thread Ewald Ertl
Hi!

I don't have a Mac and so I don't know Macpython. 

on Fri, 29 Apr 2005 07:55:20 -0500  Servando Garcia <[EMAIL PROTECTED]> wrote :
-

Servando Garcia > Hello and  thanks in advance.
Servando Garcia >   I am trying to prompt the user for some input. I need 
three values 
Servando Garcia > from the user so,I used input() like so;
Servando Garcia > Matrix = input("Matrix=")
Servando Garcia > error=input("error=")
Servando Garcia > alpha= input("alpha=")
Servando Garcia >   using  Macpython it works fine but when I use a terminal 
all I get is 
Servando Garcia > a blank line. When I try to enter at the command line I get 
this
Servando Garcia > Matrix=error=alpha=
Here on my sun i get the following:

>>> a=input("hello=")
hello=5+6
>>> a
11


When calling help on input the result is the following:

>>> help(input)
Help on built-in function input:

input(...)
input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).


So the inputvalue is evaluated in python. 

Using raw_input() gives back the entered value: 

>>> a=raw_input("hello=")
hello=myInput
>>> a
'myInput'

Perhaps this work's also on a Mac



Servando Garcia > Also I need to redirect any output from the program into 
another file, 
Servando Garcia > which is why I used the terminal in the first place. So, I 
guess I have 
Servando Garcia > two problems

On a UNIX-Shell two programms are connected via the "|" - Pipe. 
The first one writes to stdout ( sys.stdout or print ) and the second 
reads from stdin

Servando Garcia >   1. How do I redirect output using Macpython?
Servando Garcia >   2. How do I use input() while using a terminal?
Servando Garcia > 
Servando Garcia > ___
Servando Garcia > Tutor maillist  -  Tutor@python.org
Servando Garcia > http://mail.python.org/mailman/listinfo/tutor
Servando Garcia > 


--- end --
HTH 

Ewald 

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


Re: [Tutor] all methods in a module

2005-05-27 Thread Ewald Ertl
Hi!

I've the following solution: 

>>> for d in [ "random." + d for d in dir(random)]:
... if callable( eval(d) ):
... print "%30s :\n\n %s"  % ( d, eval( "%s.__doc__"  % ( d)))
... 
 random.Random :

 Random number generator base class used by bound module functions.


HTH Ewald 

on Fri, 27 May 2005 12:46:46 +0100  "Johan Meskens CS3 jmcs3" <[EMAIL 
PROTECTED]> wrote :
-

Johan Meskens CS3 jmcs3 > 
Johan Meskens CS3 jmcs3 > hello
Johan Meskens CS3 jmcs3 >
Johan Meskens CS3 jmcs3 > >>> import random
Johan Meskens CS3 jmcs3 > >>> print random.setstate.__doc__
Johan Meskens CS3 jmcs3 > Restore internal state from object returned by 
getstate().
Johan Meskens CS3 jmcs3 > 
Johan Meskens CS3 jmcs3 > 
Johan Meskens CS3 jmcs3 > my question is
Johan Meskens CS3 jmcs3 > " how can i loop through all the methods in a module 
Johan Meskens CS3 jmcs3 >   and print out their '__doc__' content ?
Johan Meskens CS3 jmcs3 > 
Johan Meskens CS3 jmcs3 > >>> for d in dir( random ):
Johan Meskens CS3 jmcs3 >   print random.???d???.__doc__
Johan Meskens CS3 jmcs3 > 
Johan Meskens CS3 jmcs3 > 
Johan Meskens CS3 jmcs3 > thanks
Johan Meskens CS3 jmcs3 > jmcs3
Johan Meskens CS3 jmcs3 > ___
Johan Meskens CS3 jmcs3 > Tutor maillist  -  Tutor@python.org
Johan Meskens CS3 jmcs3 > http://mail.python.org/mailman/listinfo/tutor
Johan Meskens CS3 jmcs3 > 


--- end --

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


Re: [Tutor] Calling a function

2005-06-09 Thread Ewald Ertl
Hi!
I don't know if I'm right here, because I've tested a simple model of what 
you're 
trying to do:


on Wed, 8 Jun 2005 23:45:59 -0700  Kevin Reeder <[EMAIL PROTECTED]> wrote :
-


Kevin Reeder > import time, makezeros
Kevin Reeder > 
Kevin Reeder > def do_timing(num_times, *funcs):

Here funcs is a tuple containing all remaining arguments of the functions. 

Kevin Reeder > totals = {}
Kevin Reeder > for func in funcs: totals[func] = 0.0
Kevin Reeder >  for x in range(num_times):
Kevin Reeder >  for func in funcs:
Kevin Reeder >  starttime = time.time()
Kevin Reeder >  apply(func)
Kevin Reeder >  stoptime = time.time()
Kevin Reeder >  elapsed = stoptime-starttime
Kevin Reeder >  totals[func] = totals[func] + elapsed
Kevin Reeder >   for func in funcs:
Kevin Reeder >   print "Running %s %d times took %.3f seconds" %
Kevin Reeder > (func.__name__, num_times, totals[func])
Kevin Reeder > 
Kevin Reeder > do_timing(100, (makezeros.lots_of_appends, 
makezeros.one_multiply))


You call do_timing() with the number of calls and one Argument, the tuple of 
functions, 
so the funcs in do_timing() is a tuple containing your tuple on the call here. 

Calling it this way should solve it: 

do_timing(100, makezeros.lots_of_appends, makezeros.one_multiply)


Here is a short extract from the Python-Shell of my test:

>>> def myfuncs( *funcs):
... for func in funcs:
... apply( func )
... 
>>> def sayHello():
... print "Hello\n"
... 
>>> myfuncs( sayHello, sayHello )
Hello

Hello

>>> myfuncs( ( sayHello, sayHello) )
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in myfuncs
TypeError: 'tuple' object is not callable


--- end --

HTH Ewald 

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


Re: [Tutor] List of regular expressions

2005-06-22 Thread Ewald Ertl
Hi Shidan!

on Wed, 22 Jun 2005 00:28:44 -0400  Shidan <[EMAIL PROTECTED]> wrote :
-

Shidan > Hi I have a list of regular expression patterns like such:
Shidan > 
Shidan > thelist = 
['^594694.*','^689.*','^241.*','^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*']
Shidan > 
Shidan > 
Shidan > Now I want to iterate thru each of these like:
Shidan > 
Shidan > for pattern in thelist:
Shidan > regex=re.compile(pattern)
Shidan > if regex.match('24110'):
Shidan > the_pattern = pattern
Shidan > .
Shidan > .
Shidan > sys.exit(0)
Shidan > 
Shidan > but in this case it will pick thelist[2] and not the list[3] as I 
wanted to,
Shidan > how can I have it pick the pattern that describes it better from the 
list.

Perhaps you can reorder "thelist" in such a way, that the more extact pattern 
come's first
thelist = 
['^594694.*','^689.*','^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*','^241.*']

So you cann exit if 
'^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*' is found, 
because here 
you want 241 followed by the number-combination which is an exacter description 
as '241.*'.


--- end --
HTH Ewald 

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


Re: [Tutor] Lists in List question

2005-06-24 Thread Ewald Ertl
Hello Phil!

the HTML-Formating look's better than the text-Version. 

on Thu, 23 Jun 2005 17:15:59 -0500  Phillip Hart <[EMAIL PROTECTED]> wrote :
-

Phillip Hart > Hello,
Phillip Hart > I've been using lists within lists for several functions, but 
have been 
Phillip Hart > unable, in loop form, to extract data from them or, in loop for, 
apply data 
Phillip Hart > to them.
Phillip Hart > 
Phillip Hart > Basically, when extracting data, it only runs 1 loop. Likewise, 
when 
Phillip Hart > initially assigning the data, it only runs 1 loop.
Phillip Hart > 
Phillip Hart > In the following example, the loop works once for x, and then a 
full loop (8 
Phillip Hart > times) for y:
Phillip Hart > 
Phillip Hart > ### 
Phillip Hart > rr1=[0,0,0,0,0,0,0,0]
Phillip Hart > rr2=[0,0,0,0,0,0,0,0]
Phillip Hart > rr3=[0,0,0,0,0,0,0,0]
Phillip Hart > rr4=[0,0,0,0,0,0,0,0]
Phillip Hart > rr5=[0,0,0,0,0,0,0,0]
Phillip Hart > rr6=[0,0,0,0,0,0,0,0]
Phillip Hart > rr7=[0,0,0,0,0,0,0,0]
Phillip Hart > rr8=[0,0,0,0,0,0,0,0]
Phillip Hart > results=[rr1,rr2,rr3,rr4,rr5,rr6,rr7,rr8]
Phillip Hart > 
Phillip Hart > 
Phillip Hart > x=0
Phillip Hart > y=0
Phillip Hart > while x<8:
Phillip Hart > while y<8:
Phillip Hart > value=x+y
Phillip Hart > results[x][y]=value
Phillip Hart > y=y+1
Phillip Hart > x=x+1
Phillip Hart > 

In the nested while-Loop's there is no reset of y during each run for an 
incremented x
so after the first turn the second while will never be run, because y is 
allways set to 8.


--- end --

HTH Ewald 

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


Re: [Tutor] Confused about error message

2005-07-04 Thread Ewald Ertl
Hi!


you're missing the except-clause in the exception-handling: 

on Sun, 3 Jul 2005 21:37:57 -0400  gelsey torres <[EMAIL PROTECTED]> wrote :
-

gelsey torres > I'm new to Python and computer programming in general. 
Eventually I
gelsey torres > got sick of just reading my programming books and typing code 
from
gelsey torres > them into the interpreter, so I decided to write a script that 
will
gelsey torres > grab files from websites and save them to the hard drive, and if
gelsey torres > they're compressed, unzip them. Here is my code:
gelsey torres > 
gelsey torres > #! /usr/bin/python
gelsey torres > # 07/03/2005
gelsey torres > # file_downloader.py - Downloads files and unzips them if they 
are a .zip file
gelsey torres > 
gelsey torres > from urllib import FancyURLopener
gelsey torres > import os.path
gelsey torres > import zlib
gelsey torres > import fnmatch
gelsey torres > 
gelsey torres > def get_file(address, filename, url):
gelsey torres > try:
gelsey torres > file_content = FancyURLopener()
gelsey torres > file_content.retrieve(address, filename)
gelsey torres > print "Finished downloading %s from %s." % (filename, 
url)
gelsey torres > except(), error:
gelsey torres > print "An error has occured:", error
gelsey torres > 
gelsey torres > def unzip_file(filename):
gelsey torres > print "Unzipping file.."
gelsey torres > for file in filename:
gelsey torres > try:
gelsey torres > file = os.path.split(filename)[2]
gelsey torres > file += zlib.decompressobj()
gelsey torres > 

Here is the catch of the  Exception missing.


gelsey torres > def main():
gelsey torres > address = raw_input("Enter the address of the site: ")
gelsey torres > url, filename = os.path.split(address) # remove path and 
keep the
gelsey torres > name of the original file
gelsey torres > get_file(address, filename, url)
gelsey torres > if fnmatch(filename, "*.zip"):
gelsey torres > unzip_file(filename)
gelsey torres > else:
gelsey torres > pass
gelsey torres > 
gelsey torres > main()
gelsey torres > response = raw_input("Do you want to run the program again? 
(y/n): ")
gelsey torres > while (response == "y"):
gelsey torres > main() 
gelsey torres > else:
gelsey torres > raw_input("\n\nPress enter to quit.")
gelsey torres > 
gelsey torres > When I ran it to test main(), I got this error:
gelsey torres > 
gelsey torres > File "file_downloader.py", line 25
gelsey torres > def main():
gelsey torres > ^
gelsey torres > SyntaxError: invalid syntax
gelsey torres > 
gelsey torres > Although sometimes it takes me awhile, I can usually spot the 
errors
gelsey torres > that I've made when they come up. I've stared at this one for 
two days
gelsey torres > and I still don't see the syntax error the interpreter is 
referring
gelsey torres > to. What am I doing wrong? I'm using Python 2.3 on Mac OS X 
version
gelsey torres > 10.3.9, and I run my scripts from Terminal.
gelsey torres > 
gelsey torres > Thank you for your consideration,
gelsey torres > 
gelsey torres > Gelsey
gelsey torres > ___
gelsey torres > Tutor maillist  -  Tutor@python.org
gelsey torres > http://mail.python.org/mailman/listinfo/tutor
gelsey torres > 


--- end --

The exception catching should solve your problem. 

HTH Ewald

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


Re: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post.

2005-07-07 Thread Ewald Ertl
Hi!


on Thu, 7 Jul 2005 01:13:48 -0600  "Nathan Pinno" <[EMAIL PROTECTED]> wrote :
-

Nathan Pinno >   Thanks Wolfram for help with that error.
Nathan Pinno > 
Nathan Pinno >   Here's another that popped up:
Nathan Pinno > 
Nathan Pinno >   Traceback (most recent call last):
Nathan Pinno > File "D:\password.py", line 68, in ?
Nathan Pinno >   for x in site.keys():
Nathan Pinno >   AttributeError: 'str' object has no attribute 'keys'
Nathan Pinno > 

The Traceback tells you on which line the error is. 
site comes from your input : site = raw_input("Site: ")
which is a string and not a dictionary.



Nathan Pinno >   How to fix it?
Nathan Pinno > 
Nathan Pinno >   Thanks,
Nathan Pinno >   Nathan Pinno
Nathan Pinno >   - Original Message - 
Nathan Pinno >   From: "Wolfram Kraus" <[EMAIL PROTECTED]>
Nathan Pinno >   To: 
Nathan Pinno >   Sent: Thursday, July 07, 2005 1:02 AM
Nathan Pinno >   Subject: Re: [Tutor] Why is this error showing up? (Original 
Message: 
Nathan Pinno > (Tutor) What's wrong with this code?) Ignore previous post.
Nathan Pinno > 
Nathan Pinno > 
Nathan Pinno >   > You wrote filename == raw_input("Filename to load: ") 
instead of
Nathan Pinno >   > filename = raw_input("Filename to load: ")
Nathan Pinno >   >
Nathan Pinno >   > HTH,
Nathan Pinno >   > Wolfram
Nathan Pinno >   >
Nathan Pinno >   > Nathan Pinno wrote:
Nathan Pinno >   >> Hi all,
Nathan Pinno >   >>
Nathan Pinno >   >> Here's one of the messages that pops up:
Nathan Pinno >   >>
Nathan Pinno >   >> Traceback (most recent call last):
Nathan Pinno >   >>   File "D:\password.py", line 77, in ?
Nathan Pinno >   >> filename == raw_input("Filename to load: ")
Nathan Pinno >   >> NameError: name 'filename' is not defined
Nathan Pinno >   >>
Nathan Pinno >   >> Why is it popping up whenever I try to load a file?
Nathan Pinno >   >>
Nathan Pinno >   >> Here's the latest code:
Nathan Pinno >   >>
Nathan Pinno >   >> # This is the code for a password protected program to 
store passwords.
Nathan Pinno >   >> password = "hello"
Nathan Pinno >   >> print "The Password Program"
Nathan Pinno >   >> print "Copyright 2005 Nathan Pinno."
Nathan Pinno >   >> print
Nathan Pinno >   >> answer = raw_input("What is the password? ")
Nathan Pinno >   >> while password != answer:
Nathan Pinno >   >> print "The password is incorrect."
Nathan Pinno >   >> answer = raw_input("What is the password? ")
Nathan Pinno >   >> def main_menu():
Nathan Pinno >   >> print "1) Add a login info card"
Nathan Pinno >   >> print "2) Lookup a login info card"
Nathan Pinno >   >> print "3) Remove a login info card"
Nathan Pinno >   >> print "4) Print Login info list"
Nathan Pinno >   >> print "5) Save login list"
Nathan Pinno >   >> print "6) Open Login list"
Nathan Pinno >   >> print "9) Exit"
Nathan Pinno >   >>
Nathan Pinno >   >> def load_login(site,filename):
Nathan Pinno >   >> in_file = open(filename,"r")
Nathan Pinno >   >> while 1:
Nathan Pinno >   >> in_line = in_file.readline()
Nathan Pinno >   >> if len(in_file) == 0:
Nathan Pinno >   >> break
Nathan Pinno >   >> in_line = in_line[:-1]
Nathan Pinno >   >> [site,id,passcard] = string.split(in_line,",")
Nathan Pinno >   >> list[site] = id and passcard
Nathan Pinno >   >> in_file.close()
Nathan Pinno >   >>
Nathan Pinno >   >> def save_login(site,filename):
Nathan Pinno >   >> out_file = open(filename,"w")
Nathan Pinno >   >> for x in site.keys():

site comes form your input :  site = raw_input("Site: ")
and is a string and not a dictionary. 
Perhaps you will use here "sites", but there are no items added to 
sites??


Nathan Pinno >   >> out_file.write(x+","+sites[x]+"\n")
Nathan Pinno >   >> out_file.close()
Nathan Pinno >   >>
Nathan Pinno >   >> menu_choice = "0"
Nathan Pinno >   >> list = {}
Nathan Pinno >   >> print "Welcome to the second half of the program."
Nathan Pinno >   >> print main_menu()
Nathan Pinno >   >> while menu_choice != "9":
Nathan Pinno >   >> menu_choice = raw_input("Choose an option: ")
Nathan Pinno >   >> if menu_choice == "1":
Nathan Pinno >   >> print "Add a login info card"
Nathan Pinno >   >> site = raw_input("Site: ")
Nathan Pinno >   >> id = raw_input("User ID: ")
Nathan Pinno >   >> passcard = raw_input("Password: ")
Nathan Pinno >   >> list[site] = id and passcard
Nathan Pinno >   >> menu_choice = raw_input("Choose an option: ")
Nathan Pinno >   >> elif menu_choice == "2":
Nathan Pinno >   >> print "Lookup a login info card"
Nathan Pinno >   >> site = raw_input("Site: ")
Nathan Pinno >   >> if site.has_key(site):
Nathan Pinno >   >> print "The ID is: ",id(site)
Nathan Pinno >   >> print "The password is: ",passcard(site)
Nathan Pinno 

Re: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post.

2005-07-07 Thread Ewald Ertl
Hello!

I just looked a little over the code, what it is perhaps ment to do now. 

As allready mentioned by Ziyad in your former post:

just call "main_menu()" 

don't print main_menu()

This calls the funciton main_men(), which prints it menu and 
after this the print-Command in this line print's the return-Value 
of the function : 
e.g. in the python-shell:

>>> def main_menu():
... print "here in main_menu"
... 
>>> print main_menu()
here in main_menu
None


The next thing is to move main_menu() into the while-Loop, 
so you see the menu every time the loop runs, otherwise it would 
after some inputs disappear from the screen. 
In every if/elif-branch you can delete the last raw_input() requesting 
for an option, because the while-Loop has it's own request at the start of
the loop. 

Here's a snap of the first 2 Options in the menu, I've changed: 
-
while menu_choice != "9":
main_menu()
menu_choice = raw_input("Choose an option: ")
if menu_choice == "1":
print "Add a login info card"
site = raw_input("Site: ")
id = raw_input("User ID: ")
passcard = raw_input("Password: ")
sitelist[site] = [id,passcard]
 Here I asign the data to the dictionary sitelist with the key "site" 
 an list with the value of id as the first entry and the value of passcard
 as the second entry
 I've renamed list to sitelist, because list itself is a builtin creating 
 a list . 
 e.g.:
 >>> a="hallo"
 >>> list(a)
 ['h', 'a', 'l', 'l', 'o']


elif menu_choice == "2":
print "Lookup a login info card"
site = raw_input("Site: ")
 as the "list"  is a dictionary we can lookup if the site is 
 available in the sitelist. 
if sitelist.has_key(site):  
print "The ID is: ",sitelist[site][0]
 the 0 Element of the list at sitelist[site] is the id and the first 
 one is the password. 

print "The password is: ",sitelist[site][1]
else:
print site," was not found."
-

I've used a list for storing the elements of id and passcard, but you could 
also use an other 
dictionary with the keys id and passcard if you like. 

The next problem is in the part of menu_choice =="3" and "4":
There is no dictionary named "numbers". Here you can also use the 
sitelist[site], ... 

I hope that help's you to change the rest of your code. 


Ewald 




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


Re: [Tutor] maximum recursion depth exceeded !

2005-07-07 Thread Ewald Ertl
Hi Mohammad!

I've never use a recursive function in python, but the error has the 
same meaning as e.g in java. 

Your function get's called and called without the end-criteria for the 
recursive call is ever met. 
I would suggest to check if the end-criteria of the recursive call is 
correct. 

I don't know if there is something like a "default" value for the maximum of 
a recursive call depth.

I just looked into the sys-Module and found the following on my Solaris 9 box:

>>> help(sys.setrecursionlimit)
Help on built-in function setrecursionlimit:

setrecursionlimit(...)
setrecursionlimit(n)

Set the maximum depth of the Python interpreter stack to n.  This
limit prevents infinite recursion from causing an overflow of the C
stack and crashing Python.  The highest possible limit is platform-
dependent.

>>> sys.getrecursionlimit()
1000
>>> 


HTH Ewald 

on Thu, 7 Jul 2005 14:54:16 +0430  Mohammad Moghimi <[EMAIL PROTECTED]> wrote :
-

Mohammad Moghimi > Hi there
Mohammad Moghimi > I wrote a recursive function a got this error how can I 
increase 
Mohammad Moghimi > maximum recursion depth. And what is its default value?
Mohammad Moghimi > -- Mohammad
Mohammad Moghimi > do you Python?!!
Mohammad Moghimi > ___
Mohammad Moghimi > Tutor maillist  -  Tutor@python.org
Mohammad Moghimi > http://mail.python.org/mailman/listinfo/tutor
Mohammad Moghimi > 


--- end --


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup.

2005-07-12 Thread Ewald Ertl
 Area"
Nathan Pinno > print "3) Volume"
Nathan Pinno > print "4) Shape Menu"
Nathan Pinno > g = input("Choice: ")
Nathan Pinno > if g == 1:
Nathan Pinno >r = input("Radius: ")
Nathan Pinno >height = input("Height: ")
Nathan Pinno >print "The Lateral Area is: ",(2*3.14*r)*height
Nathan Pinno >shape_menu()
Nathan Pinno > elif g == 2:
Nathan Pinno >r = input("Radius: ")
Nathan Pinno >height = input("Height: ")
Nathan Pinno >print "The Total Area is: 
",((2*3.14*r)*height)+(2*(3.14*(r**2)))
Nathan Pinno >shape_menu()
Nathan Pinno > elif g == 3:
Nathan Pinno >r = input("Radius: ")
Nathan Pinno >height = input("Height: ")
Nathan Pinno >print "The volume is: ",(3.14*(r**2))*height
Nathan Pinno >shape_menu()
Nathan Pinno > elif g == 4:
Nathan Pinno >shape_menu()
Nathan Pinno > else:
Nathan Pinno >print "That is not an option!"
Nathan Pinno >g = input("Choice: ")
Nathan Pinno > elif shape_opt == 7:
Nathan Pinno > print "1) Arc Length"
Nathan Pinno > print "2) Area"
Nathan Pinno > print "3) Shape Menu"
Nathan Pinno > h = input("Choice: ")
Nathan Pinno > if h == 1:
Nathan Pinno >diam = input("Diameter: ")
Nathan Pinno >print "The arc length is: ",(3.14*diam)/2
Nathan Pinno >shape_menu()
Nathan Pinno > elif h == 2:
Nathan Pinno >r = input("Radius: ")
Nathan Pinno >print "The area is: ",(3.14*(r**2))/2
Nathan Pinno >shape_menu()
Nathan Pinno > elif h == 3:
Nathan Pinno >shape_menu
Nathan Pinno > else:
Nathan Pinno >print "Sorry, incorrect entry. Please try again."
Nathan Pinno >h = input("Choice: ")
Nathan Pinno > elif shape_menu == 8:
Nathan Pinno > main_menu()
Nathan Pinno > else:
Nathan Pinno > print "Sorry, not an option."
Nathan Pinno > shape_menu()
Nathan Pinno > elif option == 3:
Nathan Pinno > temp_menu()
Nathan Pinno > if temp_option == 1:
Nathan Pinno > print "Convert degrees Kelvin to degrees Celsius."
Nathan Pinno > k = input("Degrees Kelvin: ")
Nathan Pinno > print k-273.16," degrees Celsius"
Nathan Pinno > temp_menu()
Nathan Pinno > elif temp_option == 2:
Nathan Pinno >   print "Convert Fahrenheit to Celsius"
Nathan Pinno >   f = input("Degrees Fahrenheit: ")
Nathan Pinno >   print 5/9*(f-32)," degrees Celsius"
Nathan Pinno >   temp_menu()
Nathan Pinno > elif temp_option == 3:
Nathan Pinno >   print "Convert Celsius to Fahrenheit"
Nathan Pinno >   c = input("Degrees Celsius: ")
Nathan Pinno >   print (9/5*C)+32," degrees Fahrenheit"
Nathan Pinno >   temp_menu()
Nathan Pinno > elif temp_option == 4:
Nathan Pinno >   print "Convert degrees Celsius to degrees Kelvin"
Nathan Pinno >   c = input("Degrees Celsius: ")
Nathan Pinno >   print c+273.16," degrees Kelvin"
Nathan Pinno >   temp_menu()
Nathan Pinno > elif temp_option == 5:
Nathan Pinno >   print "Convert degrees Kelvin to Fahrenheit"
Nathan Pinno >   k = input("Degrees Kelvin: ")
Nathan Pinno >   print ((k-273.16)*9/5)+32," degrees Fahrenheit"
Nathan Pinno >   temp_menu()
Nathan Pinno > elif temp_option == 6:
Nathan Pinno >   print "Convert Fahrenheit to degrees Kelvin"
Nathan Pinno >   f = input("Degrees Fahrenheit: ")
Nathan Pinno >   print (5/9*(f-32))+273.16," degrees Kelvin"
Nathan Pinno >   temp_menu()
Nathan Pinno > elif temp_option == 7:
Nathan Pinno >   main_menu()
Nathan Pinno > else:
Nathan Pinno >   print "That's not an option. Please try again"
Nathan Pinno >   temp_menu()
Nathan Pinno > elif option == 4:
Nathan Pinno >formula_menu()
Nathan Pinno >if formula_option == 1:
Nathan Pinno >   p = input("Principal: ")
Nathan Pinno >   r = input("Rate as a decimal: ")
Nathan Pinno >   t = input("Time in years: ")
Nathan Pinno >   print "Interest: ",p*r*t
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 2:
Nathan Pinno >   r = input("Rate: ")
Nathan Pinno >   t = input("Time: ")
Nathan Pinno >   print "Distance: ",r*t
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 3:
Nathan Pinno >   v = input("Velocity: ")
Nathan Pinno >   t = input("Time: ")
Nathan Pinno >   print "Uniform motion: ",v*t
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 4:
Nathan Pinno >   m = input("Mass: ")
Nathan Pinno >   v = input("Velocity: ")
Nathan Pinno >   print "Momentum: ",m*v
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 5:
Nathan Pinno >   as = input("Acceleration speed: ")
Nathan Pinno >   t = input("Time: ")
Nathan Pinno >   print "Uniformly accelerated motion: ",1/2*as*t
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 6:
Nathan Pinno >   gravity = input("Constant acceleration due to gravity: ")
Nathan Pinno >   t = input("Time: ")
Nathan Pinno >   print "Distance covered by falling body: 
",1/2*gravity*(t**2)
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 7:
Nathan Pinno >   m = input("Mass: ")
Nathan Pinno >   gravity = input("Gravity: ")
Nathan Pinno >   print "Weight: ",m*gravity
Nathan Pinno >   formula_menu()
Nathan Pinno >elif formula_option == 8:
Nathan Pinno >   main_menu()
Nathan Pinno >else:
Nathan Pinno >   print "That is not an option."
Nathan Pinno >   formula_menu()
Nathan Pinno > elif option == 5:
Nathan Pinno >print "Goodbye!"
Nathan Pinno > else:
Nathan Pinno >print "That is not an option. Please choose an option from 
the menu."
Nathan Pinno >main_menu()
Nathan Pinno > print
Nathan Pinno > 
Nathan Pinno > 
Nathan Pinno > So how do I do it?
Nathan Pinno > 
Nathan Pinno > Nathan Pinno
Nathan Pinno > http://www.npinnowebsite.ca/


--- end --


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] try except continue

2005-07-29 Thread Ewald Ertl
Hi!

I think you just want to execute the rest of the function's in someProcedure().
Perhaps this could be the solution, what you want:


>>> def someProcedure():
... for func in [ someFunc00, someFunc01, someFunc02, someFunc03 ]:
... try:
... func()
... except:
... print "Error in %s " % ( func.__name__ )
... continue
...
>>>
>>> someProcedure()
Error in someFunc00
yeah!
baby let's go
someInt is:  4

HTH Ewald



[EMAIL PROTECTED] wrote:
> hey guys, so I've been trying to get my head around the try except
> statement in Python, and ideally what I'd like is for my procedural
> program, when it runs through its steps and encounters an error, to log
> the error and pick up where it left off and keep going.  According to this
> link, 'continue' is allowed within an except or finally:
> 
> http://python.active-venture.com/ref/continue.html
> 
> I tried to run the following code, expecting to catch a NameError and
> continuing on:
> 
> def someFunc00():
>   someModulo = 6%2
>   print someModulus
> 
> def someFunc01():
>   print "yeah!"
> 
> def someFunc02():
>   print "baby let's go"
> 
> def someFunc03():
>   someInt = 2+2
>   print "someInt is: ", someInt
> 
> def someProcedure():
>   someFunc00()
>   someFunc01()
>   someFunc02()
>   someFunc03()
> 
> # copy and paste the following into IDLE, which on my machine often
> #crashes for an unknown reason, so I've taken to creating a harness that
> #imports the required library and then runs the desired programs to test
> #the desired behavior
> if __name__ == "__main__":
> import testTryCatch
> try:
>   testTryCatch.someProcedure()
> except:
> print "encountered error"
>   continue
> 
> but I get the following error:
> 
> SyntaxError: 'continue' not properly in loop
> 
> What am I doing wrong ?
> 
> ___
> 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] Question About chdir()

2005-08-08 Thread Ewald Ertl
Hi Don!

Don Parris wrote:
> The book, "Programming Python", shows an example of os.chdir() on the
> Windows platform, as follows:
>
> os.chdir(r'c:\temp')


r ... raw Strings. There will no substitution be processed.
Otherwise the "\t" ( Tab ) will be inserted in the string:


>>> print "a\tb"
a   b
>>> print r"a\tb"
a\tb
>>>


HTH Ewald

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


Re: [Tutor] Finding even and odd numbers

2007-09-19 Thread Ewald Ertl
Hi Boyks,

Boykie Mackay wrote:
> Hi guys,
> 
> I have come across a bit of code to find if a group of numbers is odd or
> even.The code snippet is shown below:
> 
> if not n&1:
> return false
> 
> The above should return false for all even numbers,numbers being
> represented by n.I have tried to wrap my head around the 'not n&1' but
> I'm failing to understand what's going on.Could someone please explain

the single '&' is a bitwise and operator.
every odd number has the first bit set so &1 returns 1.

The binray representation of :
1   0001
2   0010
3   0011
4   0100

>>> 1&1
1
>>> 2&1
0
>>> 3&1
1
>>> 4&1
0

HTH Ewald

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


Re: [Tutor] Linux app question

2005-08-18 Thread Ewald Ertl
Hi Alberto

Alberto Troiano wrote:
> Hey tutorslong time don't see...*grin*
> 
> I have a question, I've made a web page in PHP and its going to run under 
> Linux Red Hat 9.0
> 
> The page has scripts that has to be on a certain path off the system...I 
> have to make a CD to give the web page to my client and I made a script 
> using Python 2.2.2 so when he runs it, the data in the CD will be copied 
> automatically to the path where every script has to be
> 
> My question is:
> 
> Obviously I will have the cdrom in /mnt/cdrom and in order to run the 
> "installer" the user will have to type
> python /mnt/cdrom/installer.py
> 
> 1.- Is there any way that the script can be started when he mounts the CDROM 
> with the command mount /mnt/cdrom?

Sorry, for this I have no clue what to do.

But it could also be possible that CDROM's are mounted, without the permission 
to
execute programms on that filesystem  ( mount ... -o noexec ). With this option
it is not possible to execute programs on that filesystem, but I don't know the
defaults on RedHat Linux 9.0.

> 2.- Is there any way that the script could be started by typing directly 
> ./installer instead of python installer.py?
> 

When you name the installer.py simple installer, set the executeable-Right's and
insert the following line on the first one:

#!/usr/bin/env python

This will lookup the Interperter python on the system und run the File with 
this.

An other possible solution could be that, you create a Shell-Script which 
start's itself
the python-Process with the executeable-Rights set.


--
#!/usr/bin/env bash

dirName=`dirname $0`

PYTHON=`which python`

if [[ -z $PYTHON ]]; then
echo " No Python-Interperter found"
else
$PYTHON $dirName/installer.py
fi
---

Here you can also insert some other error-checking.



HTH Ewald

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


Re: [Tutor] Introspection (modules and functions)

2005-11-23 Thread Ewald Ertl
Hi!

I quick solution for a name module could be:

>>> import os
>>> for d in os.__dict__:
... a="os." + d
... if callable( eval(a) ):
... print "Callable %s" % ( eval(a))

but there should also be a recipe on activestate for that problem.
I think I've red something in the Python Cookbook

HTH,
Ewald

Negroup - wrote:
> Hi.
> 
> My application hosts a module A that contains only a (variable) number
> of functions. In another part of this application I need to know which
> functions are defined inside module A. Initially I thought to use
> __dict__, but along with the functions of module A are listed all the
> builtins too.
> 
> How is possible to obtain this information without defining
> return_all_functions() (see below)?
> 
> Actually module A is something like:
> 
> def f1():
>   pass
> 
> def f2():
>   pass
> 
> # def 
> # def ...
> 
> def return_all_functions():
> t = (f1, f2, )
> return t
> 
> Thanks
> ___
> 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] Can I get some feedback on my currency converter program

2005-12-09 Thread Ewald Ertl
Hi!

vikas mohan wrote:
> Hi all, this is my first program in python.
>  
> It's a currency converter mini-program, but I am not getting the desired
> output. What wrong am I doing here?
>  
> *Program code:*
>  
> #converts currencies to Indian rupees
> 
> def print_options():
> print "Options:"
> print " 'p' print options"
> print " 'c' convert from US Dollars to Indian Rupees"
> print " 'f' convert from Swedish Kronors to Indian Rupees"
> print " 'g' convert from British Pound Sterling to Indian Rupees"
> print " 'q' quit the program"
> 
> def rupees_from_dollars(c_doll):
> return 43*1 --*The function is supposed to multiply the value of

Here is the c_doll missing
return 43*c_doll

> dollars x 43(value of an Indian rupee)
> *def rupees_from_kronor(f_kron):
> return 8*f_kron -- *The function is supposed to multiply the value
> of kronor x 8(value of an Indian rupee)*
> def rupees_from_pounds(g_pound):
> return 68*g_pound --*The function is supposed to multiply the value
> of pounds x 68(value of an Indian rupee) *
> 
> choice = "p"
> while choice != "q":
> if choice == "c":
> Rupees = input("US Dollars:")
Rupees contains the inserted value
> print "Rupees:",--*The problem is here: I only get Rupees but
Here just the Text"Rupees:" is printed

  print "Rupees:", rupees_from_dollars(Rupees)

orprint "Rupees: %d\n" % ( rupees_from_dollars( Rupees ) )

You have to call the function to get the converted value.

> not the value multiplied as stated in the function. *
> elif choice == "f":
> Rupees = input("Swedish Kronor:")
> print "Rupees:" --*The problem is here: I only get Rupees but
> not the value multiplied as stated in the function. *
> elif choice == "g":
> Rupees = input("UK Sterling:")
> print "Rupees:"--*The problem is here: I only get Rupees but not
> the value multiplied as stated in the function. *
> elif choice != "q":
> print_options()
> choice = raw_input("option:")
> 
> -
> 
> Much appreciate your help!
> 
> VikasM
> 
> ** 
> ** 
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

HTH Ewald

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


Re: [Tutor] a class knowing its self

2006-01-19 Thread Ewald Ertl
Hi!


Ben Vinger wrote:
> Hello
> 
> I've been reading about how a class has access to its
> own 'self', so I tried the following, but it is not
> working as I would expect:
> 
> class Skill:
>def __init__(self):
>   self.history = []  
> 
>def setName(self, skill):
>   self.name = skill
> 
>def getName(self):
>   return self.name
> 
> # Assigning data to my class:  
> 
> SkillNames = [r'python', r'apache', r'mysql']
> 
> #a.)
> python = Skill()
> python.setName('python')
> print python.getName()
> 
> #b.)
> for s in SkillNames:
>   s = Skill()
>   s.setName(s)
>   print s.getName()
> 
Have a more precisely look at your code.
s.getName() does just return, what you have put into
the class with setName(). ( Reassignment of a variable to
something different what you intended ).

HTH Ewald


> Why does a work and b not?   
> 
> b returns:
> <__main__.Skill instance at 0x401e260c>
> <__main__.Skill instance at 0x401e230c>
> <__main__.Skill instance at 0x401e23ec>
> 
> why does b not return the names of the 3 instances of
> Skill?
> 
> Thanks
> Ben
> 
> 
>   
> ___ 
> To help you stay safe and secure online, we've developed the all new Yahoo! 
> Security Centre. http://uk.security.yahoo.com
> ___
> 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] smtplib with yahoo smtp server

2006-02-01 Thread Ewald Ertl
Hi!

I made a copy of the source you posted.
I just got a problem as expected when doing the session.login()
because the access-data is invalid.
The connection via the smtplib.SMTP() could be established.

Perhaps there is something wrong with your namelookup.

Can you try a call in the interactive environment for
socket.gethostname()
or
socket.gethostbyname( socket.gethostname() )

Can you resolve the hostname "smtp.mail.yahoo.com" on a commandline?
e.g. nslookup smtp.mail.yahoo.com ?

Hope this can help you

Ewald


Intercodes wrote:
> 
> Hello everyone,
> 
> I am working with a registration system for my website in mod_python. I
> needed to send mail to registered users for confirmation. Since I can't
> use my ISP's smtp server, I used yahoo's smtp server and my yahoo
> username and password  to connect and send mail using this script (see
> below). But I get the following error.
> 
> "Traceback (most recent call last):
>   File "mail.py", line 12, in ?
> session = smtplib.SMTP(smtpserver)
>   File "/usr/lib/python2.4/smtplib.py", line 255, in __init__
> addr = socket.gethostbyname(socket.gethostname())
> socket.gaierror: (-2, 'Name or service not known')
> "
> 
> I got this script from some website I can't remember and just changed
> some values to get it to work. Is is possible to send mail like this? Is
> there any other easy way to do this?
> 
> Thanks for your time.
> ---
> 
> import smtplib
> 
> smtpserver = 'smtp.mail.yahoo.com '
> AUTHREQUIRED = 1 
> smtpuser = 
> '[EMAIL PROTECTED]' //
> smtppass = '[snip]'  
> 
> RECIPIENTS = ['[EMAIL PROTECTED]']
> SENDER = '[EMAIL PROTECTED]'
> mssg = "mod python"
> 
> session = smtplib.SMTP(smtpserver)
> *if* AUTHREQUIRED:
> session.login(smtpuser, smtppass)
> smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)**
> 
> 
> -- 
> Intercodes
> 
> 
> 
> 
> ___
> 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] smtplib with yahoo smtp server

2006-02-01 Thread Ewald Ertl
Hi!



Intercodes wrote:
> Ewald,
> 
>  First off, thanks for stopping by.
> 
> >The connection via the smtplib.SMTP() could be established.
> 
> 
>  I dont think so. I think it fails before the login().
> 
> --
 ex= smtplib.SMTP('smtp.mail.yahoo.com ')
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/lib/python2.4/smtplib.py", line 241, in __init__
> (code, msg) = self.connect(host, port)
>   File "/usr/lib/python2.4/smtplib.py", line 289, in connect
> for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
> socket.gaierror: (-2, 'Name or service not known')
> 
> 

Here you get a different Traceback than in the original post.

After digging in smtplib.py here ( Python 2.3.3 )

the call should be socket.getaddrinfo( "smtp.mail.yahoo.com", 25, 0, 
socket.SOCK_STREAM );

which succeeds here at my installation.

How do you resolve your hostnames ( /etc/nsswitch.conf gives the order of 
hostname resolution )



>  >>> socket.gethostname()
> 'linux'
> -
> 
 socket.gethostbyname(socket.gethostname())
> Traceback (most recent call last):
>   File "", line 1, in ?
> socket.gaierror: (-2, 'Name or service not known')

> -- 

This should resolve your own local hostname!
The socket.gethostbyname() is a call into a shared object of Python and this 
would use
( So think I ) the standard-Libraries for resolution.

Is "linux" a valid hostname?
Does "ping linux" succeed.

I still think, that this a name resolution error on your host.

HTH Ewald

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


Re: [Tutor] smtplib with yahoo smtp server

2006-02-01 Thread Ewald Ertl
Hi!

Intercodes wrote:
> 
> My nssswitch.conf
> --
> passwd: compat
> group:  compat
> 
> hosts:  files dns
> networks:   files dns
> 
> services:   files
> protocols:  files
> rpc:files
> ethers: files
> netmasks:   files
> netgroup:   files
> publickey:  files
> 
> bootparams: files
> automount:  files nis
> aliases:files
> 
>  
> -
> 

The system looks first in the /etc/hosts-File and when there is no match found, 
the
configured DNS would be requested.

> 
> >This should resolve your own local hostname!
> >The socket.gethostbyname () is a call into a shared object of
> Python and this >would use ( So think I ) the standard-Libraries for
> resolution.
> 
> 
> You totally lost me here :)
> -
> 
> 
> >Is "linux" a valid hostname?
> >Does "ping linux" succeed.
> 
> 
> I suppose not.
> 
> linux:/srv/ # ping linux
> ping: unknown host linux
> --

Here, I think is a strange problem. You can not resolve your own hostname.
Is there no entry in /etc/hosts for linux with the IP-Address of your server?
If not, try to insert such an entry.

HTH Ewald

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


Re: [Tutor] self

2006-02-13 Thread Ewald Ertl
Hi Shuying!


Shuying Wang wrote:
> Hi,
> 
> I'm having problems understanding some code I came across:
> 
> class Singleton:
> __single = None
> def __init__( self ):
> if Singleton.__single:
> raise Singleton.__single
> Singleton.__single = self
> 
> What does passing self to Singleton.__single do?

I would say, this just sets the Singleton.__single to true and
stores the reference to the only one allowed instance of the class.

When the next time an instance of the class Singleton is requested
an exception with the first instance of Singleton is thrown.

Hope my explanation is clearly understandable in English

Ewald


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


Re: [Tutor] unknown error in simple program

2006-02-13 Thread Ewald Ertl
Hi Eli!


You have a lot of calls to input() in your code.
When requesting help on input you get the following output:

>>> help(input)
Help on built-in function input:

input(...)
input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).



As you can see, the data you input is put as argument to eval, which tries to
interpret the input as  Python-source code.

What you intended is a raw_input(). This reads the data from
standard input and returns it to you.

HTH Ewald

Eli Zabielski wrote:
> I am reading "Python Programming for the absolute beginner" and am on
> chapter 4 challenges.
> It says to create a program to let the player guess letters of the word
> (I haven't tried to incorporate a guess limit yet like it says)
> my program looks fine to me, but I get a fat juicy error when I run it
> 
> My program:
> 
> # Guess My Word
> # Players pick letters in a random secret word
> # Eli Zabielski-2/13/06
> import random
> print "Hello, I will give you 5 chances to guess letters of one of my
> secret words.\n On the final chance, you must guess the word"
> WORDS = ("python", "jumble", "difficult", "answer", "xylophone",
>  "recon", "recordable")
> word=random.choice(WORDS)
> print "The word is", len(word), "letters long."
> guess=input("guess one letter")
> tried_good=()
> tried_bad=()
> guess_count=0
> while guess not in word:
> guess_count+=1
> guess+=tried_bad
> print "Nope, try again\n"
> print "Bad tries",tried_bad   
> guess=input("\nguess one letter")
> if guess_count==4:
> "You have to guess the word now"
> guess_word=input("What say you")
> guess_word=guess_word.lower()
> while guess in word:
> print "Good, you got one"
> guess+=tried_good
> print "Bad tries",tried_bad
> print "Good tries", tried_good
> guess=input("\nguess one letter")
> if guess_count==4:
> "You have to guess the word now"
> guess_word=input("What say you")
> guess_word=guess_word.lower()
> if guess_word==word:
> print "Good, you got it!"
> elif guess_word != word:
> print "Aww, thats too bad, the word is mine forever"
> exit=input("Press enter to exit.")
> 
> 
> 
> And I get: (No matter what letter I guess)
> 
> Traceback (most recent call last):
>   File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "C:\Documents and
> Settings\Eli\Desktop\Games\Applications\Programs\Guess the word\Guess
> the word 1.0.py ", line 10, in ?
> guess=input("guess one letter")
>   File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\app.py",
> line 372, in Win32Input
> return eval(raw_input(prompt))
>   File "", line 0, in ?
> NameError: name 'e' is not defined

> 
> I have been attempting to find the problem for 2 hours now and try to
> solve it on my own, but I can't do it this time.
> 
> Thanks for the help
> 
> -- 
> Eli Zabielski
> 
> 

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


Re: [Tutor] File handling: open a file at specified byte?

2006-02-19 Thread Ewald Ertl
Hi Brian!

There are two functions for an file-Object which deliver the position in the 
file
and can seek-function to set the offset in the file:


>>> f=open(".emacs", "r" )
>>> help(f.tell)
Help on built-in function tell:

tell(...)
tell() -> current file position, an integer (may be a long integer).

>>> help( f.seek )
Help on built-in function seek:

seek(...)
seek(offset[, whence]) -> None.  Move to new file position.

Argument offset is a byte count.  Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file).  If the file is opened in text mode,
only offsets returned by tell() are legal.  Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.


HTH Ewald


Brian Gustin wrote:
> HI. This is one I cant seem to find a solid answer on:
> 
> First, some background:
> I have a log file that I wrote a python parser for it, and it works 
> great , but in the interest of saving time and memory , and also to be 
> able to read the currently active log file, say every 10 minutes , and 
> update the static file, I was trying to find some way that I can get 
> python to do this:
> 
> Open log file, read lines up to end of file, and *very important* make a 
> note of the bytes read, and stash this somewhere (I.E. "mark" the file) ,
> and then handle the parsing of said file, until all lines have been read 
> and parsed, write the new files, and close the handler.
>   say, 10 minutes later, for example, the script would then check the 
> bytes read , and *very important* start reading the file *from* the 
> point it marked (I.E. pick up at the point it bookmarked) and read from 
> that point.
> Since the log file will be active (webserver log file) it will have new 
> data to be read, but I dont want to have to read through the *entire* 
> log file all over again, just to get to the new data- I want to be able 
> ot "bookmark" where the log file was read "up to" last time, and then 
> open the file later at that point.
> 
> My current script works well, but only reads the "day old" log file 
> (post log rotate) , and it does very well, parsing as much as 3 GB in as 
> little as 2 minutes if the server isnt heavily loaded when the parser 
> runs.   basically, the webserver runs Tux , which writes a log file for 
> *all* domains on a server, and the script takes the tux log, and parses 
> it, extracting the domain for which the log entry is for, and writes a 
> new line into the domain's apache format CLF log file (this way we are 
> able to run awstats on individual domains, and get relatively accurate 
> stats)
> 
> So.. my question is- is there any way to do what I want ?
> 
> Open a live log file, read lines to x bytes, (say 845673231 bytes) , 
> make a note of this, and 10 miutes later open the same file again *AT* 
> 845673232 bytes - starting with the next byte after the bookmarked 
> point, read to end of file, and update the bookmark.
> 
> 
> Thanks for any pointers- Advice appreciated.
> Bri!
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] Unable to take input as a module

2006-02-22 Thread Ewald Ertl
Hello rakesh,

Perhaps this could take you further:

[GCC 3.3.2] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> a=__import__("inspect")
>>> a

>>> a.ismodule(a)
True


HTH Ewald

Rakesh Mishra wrote:
> hi
> 
> I am trying to write a program, which ask for user input for a name
> then determines it wither that is module or not, if module then it will
> tell  all its
> attributes, methods, function etc
> 
> my code:
> ..
> .
> import sys, types, string, inspect
> 
> input= sys.argv[1] 
> print  inspect.ismodule(input)
> 
> 
> here it always give false.  as what ever  input i take it is string .
> 
> my problem is i am not able to take input as a module
> help me out !
> thanks in advance.
> rakesh
> 
> 
> ----
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] switch-case in python

2006-02-28 Thread Ewald Ertl
Hi!

Have a look to the Python-Cookbook at ActiveState.

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

This is a recipe for simulating a switch.

HTH Ewald

铁石 wrote:
>   I know this may seem to be stupid.
> but as I found that there's no 
> switch-case control flow in python,
> an I just can't remember( or know) any 
> method to make such a control flow.
> 
> 
> 
> 
> 
> 
> ___
> 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 can a function know where it was called from

2006-03-02 Thread Ewald Ertl
Hi Ben!

After looking at the modules I detected the traceback-Module in my installation:

>>> import traceback
>>> def two():
... one()
...
>>> two()
>>> def one():
... print traceback.extract_stack()
...
>>> def two():
... one()
...
>>> two()
[('', 1, '?', None), ('', 2, 'two', None), ('', 2, 'one', 
None)]

maybe this could be a start for your investigation

HTH Ewald


Ben Vinger wrote:
> Hello
>  
> I want myfunction in the pseudocode below return something different if
> it was called from indexfunction.
>  
> def indexfunction():
> blah
>  
> def myfunction():
>x = 'whatever'
>if :
>   return x
>else:
>   return  + x + 
>  
>  
> Thanks
> Ben
> 
> 
> ----
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] odbchelper

2006-03-03 Thread Ewald Ertl
Hi!

How have you started the script? As far as I could see, in the Chapter 1 of
"Dive into Python", the odbchelper.py is just a script-File and not a module
to be imported, therefore the Exception with the "ImportError".

I do not have a Windows box here to check if the problem is with the PythonIDE.
Testing with idle ( the python ide ) under solaris  and putting the source-Code 
from Chapter 1
into the buffer, saving it and just starting with "F5" = "Run Module" just gives
the string.

Otherwise under unix just start "python odbchelper.py"  on the commandline.

HTH Ewald

Kermit Rose wrote:
> When I tried to run a program show at the beginning of "Dive into Python", 
> 
> I got.
> 
> 
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> import odbchelper
> ImportError: No module named odbchelper
> 
> 
> 
> 
  
> 
> ___
> 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] odbchelper

2006-03-03 Thread Ewald Ertl
Hi Kent!


You are absolutely right. Sorry for my bad description.

Kent Johnson wrote:
> Ewald Ertl wrote:
>> Hi!
>>
>> How have you started the script? As far as I could see, in the Chapter 1 of
>> "Dive into Python", the odbchelper.py is just a script-File and not a module
>> to be imported, therefore the Exception with the "ImportError".
> 
> It is both, if by "just a script-File" you mean a top-level program 
> intended to be run from the command line.
> 
Yes I meant a top-level-program.

> If you import odbchelper it will give you access to the 
> buildConnectionString() function. If you run it from the command line, 
> it will also run the code after
> if __name__ == "__main__":
> 
> This is pretty common - to write a module so it can be imported or used 
> as a main program. The parts you want to run only from the command line 
> are set off by this conditional.
> 

I looked at the code of odbchelper.py in Example 2.1 in my printed Version of
"Dive into Python" and there was no "import", so I assumed some problem with 
the IDE.
But the Traceback came from Example 2.5 in my version.

Thanks for your response on my attempt to help
Ewald

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


Re: [Tutor] OSError

2006-03-15 Thread Ewald Ertl
Hi Chris,
  I think I've found the problem. os.listdir() gives you all entries of 
the directory, but your
not changing to that directory. The os.path.getsize() just does not find the 
file in the directory "testFiles" under
your current directory.
See my short example below.


>>> import os
>>> os.listdir( "trace" )
['nbewer', 'installer_acb_2004-10-15.zip', 'epAnalyze.py', 'nbgene', 
'ep20051201.txt', 'IPseconLinux.sxw', 'bbaseline', 'inner-classes.patch', 
'jde-usages-0.9.1.zip', 'bleuch.ttf', 'privdebug']
>>> os.getcwd()
'/users/trinomic/ewer'
>>> import os.path
>>> os.path.isfile ( "epAnalyze.py" )
False
>>> os.path.isfile ( "trace/epAnalyze.py" )
True


HTH Ewald

Christopher Spears wrote:
> I am trying to write a function that takes a directory
> name and describes the contents of the directory (file
> name and size) recursively.  Here is what I have
> written so far:
> 
> import os, os.path
> 
> def describeDirectory(directory):
> if os.listdir(directory) == []:
> print "Empty directory!"
> else:
> for files in os.listdir(directory):
> if os.path.isdir(files):
> print files, ' is a directory!'
> else:
> print files, 'SIZE: ',
> os.path.getsize(files)
> 
> print 'Current Directory: \n'
> describeDirectory('.')
> print '\n'
> print './testFiles: \n'
> describeDirectory('./testFiles')
> 
> Here is the result:
> 
> Current Directory: 
> 
> changePeppers.py SIZE:  915
> describeDirectory.py SIZE:  481
> describeDirectory.pyc SIZE:  514
> error_log SIZE:  0
> makezeros.py SIZE:  147
> makezeros.pyc SIZE:  481
> output SIZE:  387
> pepper.txt SIZE:  601
> testFiles  is a directory!
> textWrapper.py SIZE:  619
> textWrapper.pyc SIZE:  1092
> timings.py SIZE:  567
> timings.pyc SIZE:  733
> 
> 
> ./testFiles: 
> 
> renameFiles.py SIZE: 
> Traceback (most recent call last):
>   File "describeDirectory.py", line 17, in ?
> describeDirectory('./testFiles')
>   File "describeDirectory.py", line 11, in
> describeDirectory
> print files, 'SIZE: ', os.path.getsize(files)
>   File "/usr/lib/python2.4/posixpath.py", line 139, in
> getsize
> return os.stat(filename).st_size
> OSError: [Errno 2] No such file or directory:
> 'renameFiles.py'
> 
> I don't understand the OSError.  The file
> 'renameFiles.py' is in './testFiles' directory.  Can
> someone clarify this for me?
> 
> -Chris
> 
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be a 
> color television set."
> -David Bowie
> 
> "Who dares wins"
> -British military motto
> 
> "I generally know what I'm doing."
> -Buster Keaton
> ___
> 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] oserror [errno 20]

2006-04-03 Thread Ewald Ertl
Hi,

k r fry wrote:
> Hi, I am new to this list, and also to Python.
> I am trying to get Python to loop through the directory DATADIR which 
> contains the data I want to read.  I get an error:  "oserror [errno 20] 
> : Not a directory: "Katiescint.py"
> 
> The section of code is shown below:
> 
> for subdir in os.listdir(DATADIR):  #loop through list of 


os.listdir() lists the content of the directory referenced by DATADIR.
If regular files are in this directory, these are also listed.
You have to check, if subdir is really a directory before using this any
further.

> strings
> 
>  file=FITS.Read(DATADIR+'/'+subdir+'/flux.fits') #opens 
> flux.fits file and reads
> 
>  summation=open(DATADIR+'/'+subdir+'/flux.dat','w')  #opens the 
> summation results file for writing to
> 
>  spotbyspot=open(DATADIR+'/'+subdir+'/spotflux.dat','w') #opens the 
> spot-by-spot file for writing to
> 
>  output=''
>  print'\n~~\n'+sys.argv[1]+' 
> '+subdir+'\n\n'
> 
> I would be very grateful if anyone could help me.  Thanks!
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

HTH Ewald

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


Re: [Tutor] Argument check

2006-05-04 Thread Ewald Ertl
Hi Gregor,

Maybe the module traceback could help you here.

It has same functions to extract the actual stack of the program.

HTH Ewald

Gregor Lingl wrote:
> Hi all,
> 
> I've a class with a lot of methods, for which I'd like to check argument 
> types. 
> To show you, what I mean, I've written a prototype I'm not really content 
> with.
> It goes like this (a bit revised in order to have short codelines (*mail* 
> ;-)):
> 
> class BadArgError(Exception):
>  def __init__(self, fname, var, typ, val):
>  self.fname = fname
>  self.var = var
>  self.typ = typ
>  self.val = val
>  def __str__(self):
>  return """
>  %s: argument %s must be %s!
>  %s of %s given.""" % ( self.fname, self.var,
>  self.typ, repr(self.val), type(self.val))
> 
> def checkargs(fun,locs,*typelist):
>  varnames=fun.im_func.func_code.co_varnames[1:]
>  fn = fun.__name__
>  for var, typ in zip(varnames, typelist):
>  ok = isinstance(locs[var],typ)
>  if not ok:
>  raise BadArgError(fn, var, typ, locs[var])
> 
> ## classe for testing:
> 
> class Z(object):
>  pass
> 
> class A(object):
>  def f(self,x,y):
>  checkargs(self.f, locals(), int, str)
>  def g(self,a,b,c):
>  checkargs(self.g, locals(), (int,float), Z, tuple)
> 
> 
> BadArgError works like this (interactive session):
> 
>  >>> bae = BadArgError("myfun", "myvar", str, 3)
>  >>> raise bae
> 
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  raise bae
> BadArgError:
>  myfun: argument myvar must be !
>  3 of  given.
> 
> You see, I want to the error-message to display the name of the function, 
> which 
> got the bad argument, the name of the parameter and it's expected type as 
> well 
> as the wrong argument.
> 
> Examples for it's use:
> 
>  >>> z=Z()
>  >>> a=A()
>  >>> a.f(1,"a")   #ok
>  >>> a.f(1,2)
> 
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>...
>  raise BadArgError(fn, var, typ, locs[var])
> BadArgError:
>  f: argument y must be !
>  2 of  given.
>  >>> a.g(.5, z, ())#ok
>  >>> a.g(.5, a, ())
> 
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>...
>  raise BadArgError(fn, var, typ, locs[var])
> BadArgError:
>  g: argument b must be !
>  <__main__.A object at 0x00C92F70> of  given.
> 
> (One could easily tidy up this output - that's *not* the problem)
> 
> I feel it to be cumbersome and ugly, to have to pass the function (method) 
> and 
> the locals() dictionary to every call of checkargs.
> 
> I'd very much prefer a usage of checkargs similar to:
> 
> class A(object):
>  def f(self,x,y):
>  checkargs(int, str)
>  def g(self,a,b,c):
>  checkargs((int,float), Z, tuple)
> 
> but then chackargs had to get information about its caller (name, locals) 
> from 
> elsewhere (the callstack?). I don't know if this is possible at all, not to 
> say 
> how to accomplish it.
> 
> Do you have some hints?
> Where could I find code-examples which solve similar problems?
> Would you recommend a different approach?
> 
> Regards,
> 
> Gregor
> 
> 
> 
> 
> 


-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] User input

2006-05-22 Thread Ewald Ertl
MATATA EMMANUEL wrote:
> Hi there,
> 
> Can anyone tell me how I'm having trouble executing this piece of code:
> 
> mpg = raw_input (" Enter your mileage:")
> distance = raw_input ("Enter your distance:")
> galon_price = raw_input ("Enter you cost per gallon:")
> make = "Honda"
> model = "Accord"
> ##
> print make, model, "mileage is", mpg, "miles per gallon"
> print "Total trip cost is US$", distance / (mpg * gallon_price)
> 
> I get this error when I run it:
> 
> print "Total trip cost is US$", distance / (mpg * gallon_price)
> TypeError: unsupported operand type(s) for *
> 
The type which raw_input() returns is a string, so '120'*'5' multiplies
two strings.
Perhaps you can convert your input to a type you need. ( e.g. float ), but you
have to check for a ValueError-Exception if the conversion fails.

HTH Ewald

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


Re: [Tutor] More network server questions

2006-06-20 Thread Ewald Ertl
Hello,

after looking into the docs of ServerSocket,
the class TCPServer notes the following class attributes:

Class variables that may be overridden by derived classes or
instances:

- address_family
- socket_type
- request_queue_size (only for stream sockets)
- allow_reuse_address

so, I think you've to set the allow_reuse_address for the TCPServer and
not for the RequestHandler, because this class is newly instantiated for
each request of your server.
The socket itself is bound by the TCPServer.

HTH Ewald

Tino Dai wrote:
> Hi Everybody,
> 
> I took Kent's advice, and used SocketServer instead of rolling my
> own sockets. It works pretty good except for the fact that when I exit
> and restart the program, I get a Address in use. And I remember that
> Danny told me about allow_reuse_address. So, that's where I got stuck. I
> put in that statement, but no change. What am I missing?
> 
> class FtpServer ( SocketServer.StreamRequestHandler):
> def handle(self):
> self.allow_reuse_address = 1
> self.filename=self.rfile.readline(512)
> self.filename=string.strip (self.filename)
> while (self.filename != 'exit'):
> secQueue.put(self.filename)
> Listener.sema.release()   
> self.filename=self.rfile.readline (512)
> self.filename=string.strip(self.filename)
> 
> class Listener( threading.Thread ):
> sema = threading.Semaphore()
> def __init__(self):
> self.port=4242
> self.ipAddr='140.147.241.58'
> self.wholeFilenameList=[]
> threading.Thread.__init__(self)
> #print "Done with init"
> 
> def run(self):
> server=SocketServer.TCPServer(('',self.port), FtpServer)
> print "The port is: ", self.port
> 
> 
> Thanks,
> Tino
> 
> 
> ----
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor



-- 
Ing. Ewald Ertl HartterGruppe   Phone : 
+43-3352-33085-558
trinomic Projektmanagement & Informationstechnik GmbH   Fax   : 
+43-3352-33085-600
Wiener Straße 41mailto:[EMAIL PROTECTED]
A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED]

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


Re: [Tutor] error: (10054, 'Connection reset by peer')

2006-07-10 Thread Ewald Ertl
Hello!

Grady Henry wrote:
> Here is a program that I wrote using the first example at 12.2.13
> Examples at the www.python.org  website,
>  
> # Import smtplib for the actual sending function
> import smtplib
>  
> # Import the email modules we'll need
> from email.MIMEText import MIMEText
>  
> # Open a plain text file for reading.  For this example, assume that
> # the text file contains only ASCII characters.
> fp = open('C:\Documents and Settings\User\Desktop\\text3.txt','rb')
> # Create a text/plain message
> msg = MIMEText(fp.read())
> fp.close()
>  
> # me == the sender's email address
> # you == the recipient's email address
> msg['Subject'] = 'The contents of %s' % 'C:\Documents and
> Settings\User\Desktop\\text3.txt'
> msg['From'] = '[EMAIL PROTECTED]' 
> msg['To'] = '[EMAIL PROTECTED]' 
>  
> # Send the message via our own SMTP server, but don't include the
> # envelope header.
> s = smtplib.SMTP()
> s.connect()
> s.sendmail(me, [you], msg.as_string())
> s.close()
>  
> When I run the program using IDLE, I get the following message:
>  
> Traceback (most recent call last):
>   File "C:\Documents and Settings\User\Desktop\textsender.py", line 23, in ?
> s.connect()
>   File "C:\Python24\lib\smtplib.py", line 307, in connect
> (code, msg) = self.getreply()
>   File "C:\Python24\lib\smtplib.py", line 348, in getreply
> line = self.file.readline()
>   File "C:\Python24\lib\socket.py", line 340, in readline
> data = self._sock.recv(self._rbufsize)
> error: (10054, 'Connection reset by peer')
>  
> What does this mean, and how can I fix it?
You try to connect to your localhost on Port 25 for sending email. Because of
the Windows-Error 10054 'Connection reset by peer', I think you do not have an
email server running on your server.
Perhaps you can supply your email server in smtplib.SMTP().
Here is the pydoc of the init-Method:

__init__(self, host='', port=0, local_hostname=None)
Initialize a new instance.

If specified, `host' is the name of the remote host to which to
connect.  If specified, `port' specifies the port to which to connect.
By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is raised
if the specified `host' doesn't respond correctly.  If specified,
`local_hostname` is used as the FQDN of the local host.  By default,
the local hostname is found using socket.getfqdn().

HTH
Ewald

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


Re: [Tutor] smtp error from cgi script

2006-08-03 Thread Ewald Ertl
Hi Rob,

Rob wrote:
> Hi, can someone help me interpret the error output below?
>  
> I can't tell whether this is a coding error, or a configuration error,
> in which case, it would be up to my host provider.
>  
> For privacy reasons, I have changed the actual email addresses to
> [EMAIL PROTECTED]  and [EMAIL PROTECTED]
> .  The first was the recipient and the second
> was the sender.
>  
> Thanks in advance.
> -- Rob
>  
>  
> SMTPRecipientsRefused
> Python 2.3.5: /usr/bin/python
> Wed Aug 2 20:17:33 2006
>  
> A problem occurred in a Python script. Here is the sequence of function
> calls leading up to the error, in the order they occurred.
>  
>  
>62 
>63 server = smtplib.SMTP(mailserver)
>64 failed = server.sendmail(From, To, text)
>65 server.quit() 
>66 if failed:
> failed undefined, server = , server.sendmail =
> >, From =
> '[EMAIL PROTECTED]' ,
> To = '[EMAIL PROTECTED]' , text = 'From:
> [EMAIL PROTECTED] : [EMAIL PROTECTED]
> ... 1 1
> \n\n'
>  
>  
> /usr/lib/python2.3/smtplib.py
>  in sendmail(self=, from_addr='[EMAIL PROTECTED]'
> , to_addrs=['[EMAIL PROTECTED]'],
> msg='From: [EMAIL PROTECTED] :
> [EMAIL PROTECTED] ...
> 1 1 \n\n', mail_options=[],
> rcpt_options=[])
>   685 # the server refused all our recipients
>   686 self.rset()
>   687 raise SMTPRecipientsRefused(senderrs)
>   688 (code,resp) = self.data(msg)
>   689 if code != 250:
> global SMTPRecipientsRefused = ,
> senderrs = {'[EMAIL PROTECTED]' : (550,
> 'authentication required')}
>  
> SMTPRecipientsRefused: {'[EMAIL PROTECTED]' :
> (550, 'authentication required')}
>   args = ({'[EMAIL PROTECTED]' : (550,
> 'authentication required')},)
>   recipients = {'[EMAIL PROTECTED]' :
> (550, 'authentication required')}
> 

I've not worked with smtplib, but the error (550, 'authentication required'), 
suggests
to me, that you have to login into the mail-Server, otherwise the server would 
not
accept emails.
Looking into the doc for smtplib, the Class SMTP has method for that:

login(self, user, password)
Log in on an SMTP server that requires authentication.

The arguments are:
- user: The user name to authenticate with.
- password: The password for the authentication.

If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.

This method will return normally if the authentication was successful.

This method may raise the following exceptions:

 SMTPHeloErrorThe server didn't reply properly to
  the helo greeting.
 SMTPAuthenticationError  The server didn't accept the username/
  password combination.
 SMTPExceptionNo suitable authentication method was
  found.


HTH Ewald

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


Re: [Tutor] Using my own installed python version in my directory tree.

2006-09-14 Thread Ewald Ertl
Hi
Ziad Rahhal wrote:
> Hi,
> 
> I installed pythin on Linux operating system but on my own tree
> directory. Now I want to get rid (not deleting)
> the default python installation, which means I want my own python
> version to be recognized when I use "python" command.
> 
> PYTHONPATH has nothing to do with that since it just points to modules.
> I tried to set the PATH to $HOME/python/bin but this
> didn't work.
> 
Who did you set the PATH?
I'm using different installations of python on solaris.

PATH=/where/python/is:$PATH
export PATH

After setting the PATH variable, does "which python" find your desired
python interpreter?


HTH Ewald

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