Hobie Audet | 23 Apr 05:35 2014
Picon
Picon

SMTPLIB Exception Object

I am using Python 3.3 and smtplib to generate and send some E-mail.  I am trying to figure out how to handle some exceptions, but some of the documentation has me confused.  Specifically, the documentation on the SMTPRecipientsRefused exception says:

exception smtplib.SMTPRecipientsRefused

All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.

But where is the "recipients" attribute?  More specifically, what is it an attribute of?

My code looks something like this:

        server = smtplib.SMTP(name,port)
         server.login(userid, password)
        try:
             server.sendmail(fromline, tolist, msg)
          except smtplib.SMTPRecipientsRefused:
              (here's where I need to access the recipients attribute)

I have tried server.recipients, but get an attribute error (no such attribute).  I've also tried:

          smtplib.recipients
          smtplib.SMTPRecipientsRefused.recipients

and all these indicate that there is no attribute "recipients".

So where is that "recipients" attribute? 

Thanks.

Hobie Audet
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Patti Scott | 23 Apr 01:18 2014

methods of sorting

I'm practicing with lists.  I was looking for documentation on sorting with cmp() because it isn't immediately clear to me how comparing items two at a time can sort the entire list.  Identify max or min values, yes, but not sort the whole list.  So, the Sorting HOW TO (Dalke, Hettinger)  posted on python.org goes into detail on using a key parameter for sorted() and .sort(), and using operator module functions. 

How obsolete are the cmp() and the decorate-sort-undecorate methods?  To be understood but probably not used in new code?

Python Programming, Zelle;  Python 2.7.3,  PowerShell, Notepad ++
I tried several means of sorting for exercises, eg

# sortgpa3.py
# extended to let user print report out by name,GPA or credit hours

from gpa import Student, makeStudent
   
def readStudents(filename):
    infile = open(filename, 'r')
    students = []
    for line in infile:
        students.append(makeStudent(line))
    infile.close()
    return students
   
def writeStudents(students, filename):
    outfile = open(filename, 'w')
    for s in students:
        outfile.write("%0.2f\t%s\t%0.2f\t%0.2f\n" % (s.gpa(),s.getName(), s.getHours(), s.getQPoints()))
    outfile.close()
   
def cmpGPA(s1, s2):
    #function compares two students based on GPA
    return cmp(s1.gpa(), s2.gpa())

def cmpHours(s1, s2):
    #function compares two students based on credits
    return cmp(s1.getHours(), s2.getHours())
   
def cmpNames(s1, s2):
    #function compares two students' names
    return cmp(s1.getName(), s2.getName())
   
def main():
    print "This program sorts student grade information by GPA."
    order = raw_input("Do you want results printed by name, credits or GPA? ")
    filename = raw_input("Enter the name of the data file: ")
    data = readStudents(filename)
    if order[0] == ('c' or 'C'):
        data.sort(cmpHours)
    elif order[0] == ('g' or "G"):
        data.sort(cmpGPA)
    else:
        data.sort(cmpNames)
    filename = raw_input("Enter a name for the output file: ")
    writeStudents(data, filename)
   
    print "The data has been written to file %s." % (filename)
   
       
main()


or,

def main():
    print "This program sorts students based on user request."
    filename = raw_input("Enter name of the file containing student data: ")
    data = readStudents(filename)
    order = raw_input("Choose the field on which to sort students (name, GPA or credits): ")
    #print order[0]
    if order[0] == ('n' or "N"):
        tuples = [(student.getName(), student) for student in data]
        tuples.sort()
        data = [(tuples[i][1]) for i in range(len(tuples))]
        #data.sort()
       
    elif order[0] == ('c' or "C"):
        tuples = [(student.getHours(), student) for student in data]
        tuples.sort()
        data = [(tuples[i][1]) for i in range(len(tuples))]
       
    elif order[0] == ('g' or "G"):
        tuples = [(student.gpa(), student) for student in data]
        tuples.sort()
        data = [(tuples[i][1]) for i in range(len(tuples))]
   
    filename = raw_input("Enter a name for the output file: ")
    writeStudents(data, filename)
    print "The data has been written to %s ." % (filename)
   
if __name__=='__main__':
    main()

or,

def main():
    print "This program sorts students based on user request."
    filename = raw_input("Enter name of the file containing student data: ")
    data = readStudents(filename)
    order = raw_input("Choose the field on which to sort students (name, GPA or credits): ")
    print order[0]
    if order[0] == ('g' or "G"):
        data = sorted(data, key=lambda student: student.gpa())
    elif order[0] == ('c' or "C"):
        data = sorted(data, key=lambda student: student.getHours())
    elif order[0] == ('n' or "N"):
        data = sorted(data, key=lambda student: student.getName())
    filename = raw_input("Enter a name for the output file: ")
    writeStudents(data, filename)
    print "The data has been written to %s ." % (filename)
   
if __name__=='__main__':
    main()
   

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
baidusandy | 22 Apr 18:13 2014

loop couldn't work well and file couldn't close

I'm a newbie to Python. I want to make python useful to my work, to write a script for get some data out. But there are some setbacks. I really needs your help. Please, help me.

-------the first one--------------
for x in range(1,a):
  tem=open('results\\temp'+str(x))
  tem.seek(0)
  i_line=tem.readline()
  while i_line:
    i_list=i_line.split('\t')
    if float(i_list[1])<float(b[x]):
      o=open('results\\'+str(x),'a')
      o.write(i_line)
      o.close
    else:
      tem02=open('results\\temp'+str(x+1),'a')
      tem02.write(i_line)
      tem02.close
    i_line=tem.readline()
  tem.close

for x in range(a,a+1):
  close('results\\temp'+str(x))
  os.rename('results\\temp'+str(x),'results\\'+str(x))
## for the last line, the code couldn't work. I run the script in Windows XP, i don't know if there is something to do with the OS.

--------for another question:-----------
for x in range (a,a+1):
  m=open(01)
  m_line=m.readline()
  b=open('02','w')
  while m_line:
    b.write(m_line)
    m_line=m.readline()
  b.close
  m.close
## for this one, file 02 and 01are not the same. to tell the truth, the last line of 01 has not been written into file 02. What's wrong?

I hope you guys can help me.
Thank you all very much.


_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
shawn wilson | 22 Apr 11:14 2014
Picon

subprocess not returning

This works when I have a class for ldd and nothing else, but when I
run it like this:
https://gist.github.com/ag4ve/11171201

I don't get any of the libraries and I can't figure out where it's failing.
['fattr', [['/testroot', 0, 0, 777], ['/bin/dash']]]
HERE1 [/testroot]
HERE2 [/bin/dash]
['ldd', ['/lib/x86_64-linux-gnu/libc.so.6', '/lib64/ld-linux-x86-64.so.2']]
HERE2 [/lib/x86_64-linux-gnu/libc.so.6]
['ldd', ['/lib64/ld-linux-x86-64.so.2']]
HERE2 [/lib64/ld-linux-x86-64.so.2]
['ldd', ['statically']]
HERE1 [statically]
HERE2 [/lib64/ld-linux-x86-64.so.2]
['ldd', ['statically']]
HERE1 [statically]
[   'filelist',
    [['/testroot', 0, 0, 777], ['/bin/dash', 0, 0, '755'], [[[]], []]]]

Obviously it's returning something - but no usable info.
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Jorge Leon | 22 Apr 15:48 2014
Picon

inheritance and super() function in python

Good day,


I have programmed a base class for an environment I have with no problem, but when it comes to referencing the base class's constructor in the derived class's constructor I have been getting errors: 
 
TypeError: Error when calling the metaclass bases
    module.__init__() takes at most 2 arguments (3 given)

Here's how my base class' constructor looks like (position =  [x, y, z]):
class Obstacle:
    def __init__(self,position):
        self.position = position

Here's how my derived class's constructor looks like

class Cylinder(Obstacle):
   def __init__(self,position, height, radius):
       super(Obstacle,self).__init__(position)

I have no idea where the 3 given arguments are being taken from. I have modified the code on the super line just in case I missed something but that has not changed a thing. I have read that in Python you may be able to double reference, but there are no other classes interfacing the base and derived class. 

If anyone has had some prior experience with this I'd appreciate your input. 

Regards,


Jorge
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Suhana Vidyarthi | 22 Apr 03:16 2014
Picon

Help needed with Python programming

My knowledge of coding is fairly limited and I am having a hard time writing a Python code which might be pretty simple for you :-)

Here is what I am doing and I need help with:

I have a python code that shows a set of shortest paths between nodes A and B. Now I have to select the least risky path among them. To do that I have to consider the risk values of each link. I know how to calculate the path's risk using its link value.

For example: There is a path between node A and B wiht two links. Probability of failure for link 1 is 0.001 and for link 2 is 0.003. Here is the link with its risk values:                                                               A o--------------------o---------------------o B
                                           0.001               0.003
So the probability of the link being down will be: 1 - (0.999 x 0.997) = 0.996003

You can find the attached file with disaster risk values of each link.

For instance; first line is : 1,3,5,0.03   --> this means, first disaster affects links 1-3 and 5-0 and its occurrence rate is 0.03. So you need to assign link (1-3)'s risk to 0.03. 
Then you will continue with the next disaster which is the one in the next line. Note that, if a link gets affected by 2 disasters, you will add the probability of those 2 disasters to find that link's risk.

If anyone can help me code the first line, I will be able to do the rest. You need use "array list" and some functions like "file reader" and "delimiter" I guess.

Thanks in advance.
1,3,5,0.03
2,3,5,5,4,0.11
3,3,5,5,4,5,8,0.04
2,5,8,7,8,0.04
3,14,10,14,13,17,13,0.04
1,14,18,0.06
4,10,13,14,13,17,13,12,13,0.04
4,11,6,11,9,11,12,11,19,0.08
3,19,20,15,20,21,20,0.24
1,21,20,0.05
3,20,21,21,16,21,22,0.27
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Stephen Mik | 21 Apr 20:12 2014

Beginning Python 3.4.0 Programmer:Stephen Mik: Cannot get input variable to make While Loop conditional to work

Dear Python Community:
    I am new to Python,with only about a month's experience. I am writing Python 3.4.0 code that apparently isn't doing what it should be doing. Specifically, I am inputting or trying to input,a Sentry Variable to a While Loop. I want to test out the Main program" While" Loop before I add an inner "While" Loop. The program I have written,when run on the Python 3.4.0 Shell,does not stop for input of the "While" Sentry Variable,it just gives a program error: "Value of smv_grandVariable undefined". What am I doing wrong here? I'll try to post that part of the Code that is malfunctioning as well as Python Shell 3.4.0 Traceback Analysis. Please help if you can,this program is due on Thursday the 22nd of April,2014.

 

#CS 110A Spring 2014 Sect 4988 Assignment 4
#MODIFIED GUESS MY NUMBER PROGRAM
#Date April ,2014
#Programmer Stephen W. Mik
#This program is modified after a version found
#in the TextBook "Python Programming 3rd Edition"
#by Michael Dawson Copyright 2010;ISBN-13: 978-1-4354-5500-9
#Or the Alternate ISBN-10: 1-4354-5500-2.
#It is based on the material found on page 50,and pages 81-84
#of the Book, along with a downloaded basic program Structyre
#"guess_my_number" ,found in the book companion's Website Files 
#"www.courseptr.com/downloads" Chapter 3.
######EXPLANATION OF GUESS MY NUMBER###################################################
#This program uses a random number generator(supplied by Python 3.4.0) to
#to pick a changeable number between 1 and 60. The User is prompted to guess the number
#by inputting a guess at the prompt. The user is then advised whether the correct number
#has been guessed. If it has been guessed correctly,the user is congratulated. If the number
#has not been guessed correctly,the attempt is noted and quantified. then the user is told whether
# the guess number was too large (and then for the user to guess a lower number) or the number
#guessed was too small (and in this case for the user to guess a higher number). The number of
#attempted non-successful guesses is accumulated and totalled and then when finally the User guesses
#the correct number ; the guess attempts are outputted along with Congatulations. The User is queried
#if they want to play the game again,if not,the Program ends.
##########################################################################################
####MAIN PROGRAM SECTION########################
#Use the random import module for a random number between 1 and 60

import random
print("\tWelcome to the Guess My Number Game! ")
print("\n The Mysterious Number to guess is between 1 and 60. ")
print("Try to guess the Mystery Number in as few tries as you can.\n")

#Enter Main Query Loop
print("Do you want to play the game?\n")
print("Enter a 1 to play or 0 to exit:")
 
input(smv_grandVariable)
while (smv_grandVariable == 1 and smv_grandVariable != 0):
	#Enter the play games main loop area















	#Take Control of the main While Loop
	print("Do you want to run the Guess My Number game again? \n")
	print("IF so, 1 to play again or 0 to not play \n")
	input(smv_grandVariable)
	#end of main control Loop
#print out ending comments
print("Program is Ended")



input("\n\nPress the enter key to exit. ")
#End of Program 
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
	Welcome to the Guess My Number Game! 

 The Mysterious Number to guess is between 1 and 60. 
Try to guess the Mystery Number in as few tries as you can.

Do you want to play the game?

Enter a 1 to play or 0 to exit:
Traceback (most recent call last):
  File "E:\My Code\assignment4.py", line 37, in <module>
    input(smv_grandVariable)
NameError: name 'smv_grandVariable' is not defined
>>> 
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Geocrafter . | 21 Apr 20:41 2014
Picon

Error

im trying to make a board, and is detecting the pieces. Here is my code:http://pastebin.com/L3tQLV2g And here is the error: http://pastebin.com/4FiJmywL  Do you knwo hwo to fix it?

_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
rail shafigulin | 21 Apr 23:05 2014
Picon

Groups of mutually exclusive options

Does anybody know if there is a way to specify groups of mutually exclusive options using argparse module?

Currently argpase allows to specify mutually exclusive options in the following way
>>> parser = argparse.ArgumentParser(prog='PROG') >>> group = parser.add_mutually_exclusive_group() >>> group.add_argument('--foo', action='store_true') >>> group.add_argument('--bar', action='store_false') >>> parser.parse_args(['--foo']) Namespace(bar=True, foo=True) >>> parser.parse_args(['--bar']) Namespace(bar=False, foo=False) >>> parser.parse_args(['--foo', '--bar']) usage: PROG [-h] [--foo | --bar] PROG: error: argument --bar: not allowed with argument --foo
What I need is a way to specify groups of mutually exclusive options.  In other words
>>> parser = argparse.ArgumentParser(prog='PROG') >>> group1 = parser.add_argument_group() >>> group2 = parser.add_argument_group() >>> group1.add_argument('--foo', action='store_true') >>> group1.add_argument('--bar1', action='store_false') >>> group2.add_argument('--foo2', action = 'store_true') >>> group2.add_argument('--bar2', action = 'store_false') >>> mutually_exclusive_group = parser.add_mutually_exclusive_argument_group() >>> mutually_exclusive_group.add_group(group1) >>> mutually_exclusive_group.add_group(group2) >>> parser.parse_args(['--foo1', '--bar1', '--bar2']) usage: PROG [-h] [--foo1, --bar1] | [--foo2, --bar2] PROG: error: argument --foo1 or bar1 not allowed with argument --foo2 or bar2
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Saba Usmani | 20 Apr 20:06 2014

Recognising Errors

Hi,

I have designed some code, but I want it to be able to recognize invalid inputs - such as a binary number with more than 8 digits or non-binary values. What do I have to add and where do I add it?

print "Welcome to the binary -> decimal / decimal -> binary converter!"
loop = True
while loop:
    choice = raw_input("Enter b to convert from binary to decimal, d to convert from decimal to binary or e to exit")
    if choice == "b":
        decimal_num = 0
        binary_num = 0
        factor = 1;
        binary_num = raw_input ("Enter Binary Number:")
        binary_num=binary_num.lstrip("0")
        binary_num = int(binary_num)
        while(binary_num > 0):
            if((int(binary_num) % 10) == 1):
                decimal_num += factor
            binary_num /= 10
            factor = factor * 2
        print "The Decimal Equivalent is: ", decimal_num
       
    elif choice == "d":
        z=0
        n=int(input('Enter Decimal Number: '))        
        z=n
        k=[] # array
        while (n>0):
            a=int(float(n%2))
            k.append(a)
            n=(n-a)/2
        k.append(0)
        string=""
        for j in k[::-1]:
            string=string+str(j)
        print('The Binary Equivalent is %d is %s'%(z, string))
 
    elif choice == "e" :
        print "Thanks For Using This Converter!"
        loop = False


If for some reason you can't read this code properly as outlook has formatted it to look messy/cluttered; you do not have to respond. 

Thanks
_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Vipul Sharma | 19 Apr 22:48 2014
Picon

equality check difference

Hello,

Suppose we want some block of code to be executed when both 'a' and 'b' are equal to say 5. Then we can write like :

if a == 5 and b == 5:
    # do something

But a few days ago, I just involuntarily wrote a similar condition check as :

if a == b and b == 5:
    # do something 

which made me think, is there any difference between the two ?

Is there any difference, any difference in the process of evaluation or execution ? and also which one is the better ?

I think this is a general programming question and not specifically for python.

P.S. : Newbie here :)

Thanks.
Regards,
Vipul Sharma



_______________________________________________
Tutor maillist  -  Tutor <at> python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Gmane