0

I have tried countless times to debug the following function, as upon execution, the entire program crashes, with

Process finished with exit code 0

From what I can see from the function, their is no explicit "kill program" command used. I'm just not sure what is wrong with the function, and neither is the IDE.

I'm just asking for a second pair of eyes.

def CreateScoutCensus():
    #Create Word Document
    doc = docx.Document()
    run = doc.add_paragraph().add_run()
    # Apply Style
    Tstyle = doc.styles['Normal']
    font = Tstyle.font
    font.name = "Nunito Sans"
    font.size = Pt(48)
    Title = doc.add_paragraph()
    TRun = Title.add_run("Scout Census")
    TRun.bold = True
    doc.add_picture('Scouts_Logo_Stack_Black.png', width=Inches(4.0))

    Hstyle = doc.styles['Normal']
    Headfont = Hstyle.font
    Headfont.name = "Nunito Sans"
    Headfont.size = Pt(22)
    Heading = doc.add_paragraph("Statistics:")
    Heading.bold = True
    Stats = doc.add_paragraph()
    #Create bullet point list
    Stats.style = 'List Bullet'
    # Gather Stats
    #Obtain the total number of USERS in the system
    mycursor.execute("SELECT * FROM usercredentials")
    AllUsers = mycursor.fetchall()
    NoOfUsers = 0
    for i in AllUsers:
        NoOfUsers = NoOfUsers + 1
    #Obtain the number of SCOUTS in the system
    mycursor.execute("SELECT * FROM scoutinfo")
    AllScouts = mycursor.fetchall()
    NoOfScouts = 0
    for j in AllScouts:
        NoOfScouts = NoOfScouts + 1

    #Obtain the number of PARENTS in the system
    mycursor.execute("SELECT * FROM parentinfo")
    AllParents = mycursor.fetchall()
    NoOfParents = 0
    for j in AllParents:
        NoOfParents = NoOfParents + 1

    #Obtain the number of YOUNG LEADERS in the system
    mycursor.execute("SELECT * FROM youngleaderinfo")
    AllYoungLeader = mycursor.fetchall()
    NoOfYL = 0
    for j in AllYoungLeader:
        NoOfYL = NoOfYL + 1

    #Obtain the number of LEADERS in the system
    mycursor.execute("SELECT * FROM leaderinfo")
    AllLeaders = mycursor.fetchall()
    NoOfLeaders = 0
    for j in AllLeaders:
        NoOfLeaders = NoOfLeaders + 1

    #Obtain all Ethnicitys from scoutinfo in database
    mycursor.execute("SELECT Ethnicity FROM scoutinfo")
    AllEthnicity = mycursor.fetchall()
    NoOfWE = 0
    NoOfWW = 0
    NoOfWS = 0
    NoOfWNI = 0
    NoOfWB = 0
    NoOfWI = 0
    NoOfWG = 0
    NoOfWO = 0
    NoOfWBC = 0
    NoOfWBA = 0
    NoOfWA = 0
    NoOfI = 0
    NoOfP = 0
    NoOfB = 0
    NoOfC = 0
    NoOfA = 0
    NoOfCA = 0
    NoOfAR = 0
    NoOfO = 0
    NoOfCAR = 0

    #Increment appropriate variable for each instance of ethnicity
    for j in AllEthnicity:
        if j[0] == ("White: English"):
            NoOfWE = NoOfWE + 1
        if j[0] == ("White: Welsh"):
            NoOfWW = NoOfWW + 1
        if j[0] == ("White: Scottish"):
            NoOfWS = NoOfWS + 1
        if j[0] == ("White: Northern Irish"):
            NoOfWNI = NoOfWNI + 1
        if j[0] == ("White: British"):
            NoOfWB = NoOfWB + 1
        if j[0] == ("White: Irish"):
            NoOfWI = NoOfWI + 1
        if j[0] == ("White: Gypsy"):
            NoOfWG = NoOfWG + 1
        if j[0] == ("White: Other"):
            NoOfWO = NoOfWO + 1
        if j[0] == ("White and Black: Caribbean"):
            NoOfWBC = NoOfWBC + 1
        if j[0] == ("White and Black: African"):
            NoOfWBA = NoOfWBA + 1
        if j[0] == ("White and Asain"):
            NoOfWA = NoOfWA + 1
        if j[0] == ("Indian"):
            NoOfI = NoOfI + 1
        if j[0] == ("Pakistani"):
            NoOfP = NoOfP + 1
        if j[0] == ("Bangladeshi"):
            NoOfB = NoOfB + 1
        if j[0] == ("Chinese"):
            NoOfC = NoOfC + 1
        if j[0] == ("African"):
            NoOfA = NoOfA + 1
        if j[0] == ("Arab"):
            NoOfAR = NoOfAR + 1
        if j[0] == ("Caribbean"):
            NoOfCAR = NoOfCAR + 1
        if j[0] == ("Other"):
            NoOfO = NoOfO + 1

    # Defining Labels For Pie Chart
    Labels = ["White: English", "White: Welsh", "White: Scottish", "White: Northern Irish", "White: British",
          "White: Irish", "White: Gypsy", "White: Other", "White and Black: Caribbean", "White and Black: African",
          "White and Asain", "Indian", "Pakistani", "Bangladeshi", "Chinese", "African", "Caribbean", "Arab",
          "Other"]
    # Defining Data Variables For Each Slice Of The Pie Chart
    Slices = [NoOfWE, NoOfWW, NoOfWS, NoOfWNI, NoOfWB, NoOfWI, NoOfWG, NoOfWO, NoOfWBC, NoOfWBA, NoOfWA, NoOfI, NoOfP,
          NoOfB, NoOfC, NoOfA, NoOfCA, NoOfCAR, NoOfAR, NoOfO]

    #Removal of any Labels and Slices of Ethnicities not present
    if NoOfWE == 0:
        Labels.remove("White: English")
        Slices.remove(NoOfWE)
    if NoOfWW == 0:
        Labels.remove("White: Welsh")
        Slices.remove(NoOfWW)
    if NoOfWS == 0:
        Labels.remove("White: Scottish")
        Slices.remove(NoOfWS)
    if NoOfWNI == 0:
        Labels.remove("White: Northern Irish")
        Slices.remove(NoOfWNI)
    if NoOfWB == 0:
        Labels.remove("White: British")
        Slices.remove(NoOfWB)
    if NoOfWI == 0:
        Labels.remove("White: Irish")
        Slices.remove(NoOfWI)
    if NoOfWG == 0:
        Labels.remove("White: Gypsy")
        Slices.remove(NoOfWG)
    if NoOfWO == 0:
        Labels.remove("White: Other")
        Slices.remove(NoOfWO)
    if NoOfWBC == 0:
        Labels.remove("White and Black: Caribbean")
        Slices.remove(NoOfWBC)
    if NoOfWBA == 0:
        Labels.remove("White and Black: African")
        Slices.remove(NoOfWBA)
    if NoOfWA == 0:
        Labels.remove("White and Asain")
        Slices.remove(NoOfWA)
    if NoOfI == 0:
        Labels.remove("Indian")
        Slices.remove(NoOfI)
    if NoOfP == 0:
        Labels.remove("Pakistani")
        Slices.remove(NoOfP)
    if NoOfB == 0:
        Labels.remove("Bangladeshi")
        Slices.remove(NoOfB)
    if NoOfC == 0:
        Labels.remove("Chinese")
        Slices.remove(NoOfC)
    if NoOfA == 0:
        Labels.remove("African")
        Slices.remove(NoOfA)
    if NoOfCAR == 0:
        Labels.remove("Caribbean")
        Slices.remove(NoOfCAR)
    if NoOfAR == 0:
        Labels.remove("Arab")
        Slices.remove(NoOfAR)
    if NoOfO == 0:
        Labels.remove("Other")
        Slices.remove(NoOfO)

    Slices.remove(0)
    # Create Pie Chart Of Ethnicitys
    Cols = ['g', 'y', 'c', 'm', 'r', 'b']
    # Plot
    plt.pie(Slices, labels=Labels, colors=Cols,
        autopct='%1.1f%%', shadow=True, startangle=140)

    plt.axis('equal')
    plt.title("Ethnicity Scouts")
    EPieChart = plt.gcf()
    #Save pie chart
    pylab.savefig("EthnicityPieChart.png", bbox_inches='tight')
    EPieChart.savefig("EthnicityPieChart.png", bbox_inches='tight')
    #Write data to Scout Census doc
    StatOne = Stats.add_run("No Of Users: " + str((NoOfUsers)))
    StatTwo = Stats.add_run("\nNo Of Scouts: " + str((NoOfScouts)))
    StatThree = Stats.add_run("\nNo Of Parents: " + str((NoOfParents)))
    StatFour = Stats.add_run("\nNo Of Young Leaders: " + str((NoOfYL)))
    StatFive = Stats.add_run("\nNo Of Leaders: " + str((NoOfLeaders)))
    #Add piechart to doc
    doc.add_picture('EthnicityPieChart.png', width=Inches(4.0))
    #Save document
    doc.save("ScoutCensus.docx")
    plt.clf()
    #Gender Pie Chart
    # Defining Labels For Pie Chart
    LabelsG = ["Male","Female","Other"]
    # Defining Data Variables For Each Slice Of The Pie Chart
    NoOfMale=0
    NoOfFemale=0
    NoOfOther=0
    Male=("Male")
    Female=("Female")
    Other=("Other")
    #Count Number Of Males
    GetMalesSQL="SELECT COUNT(*) FROM scoutinfo WHERE gender=%s"
    mycursor.execute(GetMalesSQL,(Male,))
    myresults=mycursor.fetchone()
    NoOfMale=myresults[0]
    #Count Number Of Females
    GetFemaleSQL="SELECT COUNT(*) FROM scoutinfo WHERE gender=%s"
    mycursor.execute(GetMalesSQL,(Female,))
    myresults=mycursor.fetchone()
    NoOfFemale=myresults[0]
    #Count Number Of Others
    GetOtherSQL="SELECT COUNT(*) FROM scoutinfo WHERE gender=%s"
    mycursor.execute(GetMalesSQL,(Other,))
    myresults=mycursor.fetchone()
    NoOfOther=myresults[0]
    SlicesG = []
    SlicesG = [NoOfMale,NoOfFemale,NoOfOther]
    #Remove any slices with no data
    if NoOfMale==0:
        SlicesG.remove(0)
        LabelsG.remove("Male")
    if NoOfFemale==0:
        SlicesG.remove(0)
        LabelsG.remove("Female")
    if NoOfOther==0:
        SlicesG.remove(0)
        LabelsG.remove("Other")

    # Create Pie Chart Of Gender
    Cols = ['b','r','g']
    # Plot
    plt.pie(SlicesG, labels=LabelsG, colors=Cols,
        autopct='%1.1f%%', shadow=True, startangle=140)
    plt.axis('equal')
    plt.title("Gender Diversity Of Scouts")
    GPieChart = plt.gcf()
    pylab.savefig("GenderPieChart.png", bbox_inches='tight')
    GPieChart.savefig("GenderPieChart.png", bbox_inches='tight')
    doc.add_picture('GenderPieChart.png', width=Inches(4.0))
    doc.save("ScoutCensus.docx")
    plt.close(GPieChart)
    #Age BarChart
    #Range of appropriate age values for SCOUTS
    AgeDef=[9,10,11,12,13,14,15,16]
    Values=[]
    Ages=[]
    y_pos= np.arange(len(AgeDef))
    #Count number of Scouts of certain age
    mycursor.execute("SELECT age FROM scoutinfo")
    myresults=mycursor.fetchall()
    for i in myresults:
        Ages.append(int(i[0]))
    NoOf9=Ages.count(9)
    NoOf10 = Ages.count(10)
    NoOf11 = Ages.count(11)
    NoOf12 = Ages.count(12)
    NoOf13 = Ages.count(13)
    NoOf14 = Ages.count(14)
    NoOf15 = Ages.count(15)
    NoOf16 = Ages.count(16)
    Values=[NoOf9,NoOf10,NoOf11,NoOf12,NoOf13,NoOf14,NoOf15,NoOf16]
yint = range(min(Values), math.ceil(max(Values)) + 1)
    #Plot graph
    plt.bar(y_pos, Values, align="center", alpha=0.5)
    plt.yticks(yint)
    plt.xticks(y_pos,AgeDef)
    plt.ylabel("No Of Scouts Of Age")
    plt.xlabel("Age")
    plt.title("Number Of Scouts By Age")
    ScoutAgeBarChart = plt.gcf()
    pylab.savefig("ScoutAgeBarChart.png", bbox_inches='tight')
    ScoutAgeBarChart.savefig("ScoutAgeBarChart.png", bbox_inches='tight')
    #Save image to document
    doc.add_picture('ScoutAgeBarChart.png', width=Inches(4.0))
    doc.save("ScoutCensus.docx")
    tk.messagebox.showinfo("Success!","Scout Census Created!")
    os.system("start ScoutCensus.docx")
    return
Lyra Orwell
  • 1,048
  • 4
  • 17
  • 46
  • That's too many variables. You can use a dictionary for storing counts for appropriate ethnicity. – Austin Mar 16 '19 at 15:39
  • 1
    Sounds like your program runs perfectly, but it does nothing. Are you calling the function at the end ? – PRMoureu Mar 16 '19 at 15:39
  • @PRMoureu No it doesn't call another function at the end. Should it? – Lyra Orwell Mar 16 '19 at 15:41
  • @Austin Thanks for your suggestion. – Lyra Orwell Mar 16 '19 at 15:41
  • Try to add `CreateScoutCensus()` at the end to call and execute the whole function – PRMoureu Mar 16 '19 at 15:42
  • 1
    "finished with exit code 0" isn't a crash at all. It's what's *supposed* to happen when a program is done running -- aka it's finished all the code in the file and falls out the end. Which makes perfect sense here, since all you have is a `def`, and nothing that actually tells that function to be run... so it defines the function (but doesn't call it), and then is finished running and exits successfully. – Charles Duffy Mar 16 '19 at 15:43
  • @PRMoureu I do call the function in the system, I just showed you the function because I thought their was a command in the function which caused the program to exit. – Lyra Orwell Mar 16 '19 at 15:45
  • A question needs to provide a [mcve] -- the *shortest possible code* that reproduces the specific issue you're asking about when run *without modifications*. Adding a function call is, in this context, a modification. – Charles Duffy Mar 16 '19 at 15:46
  • @CharlesDuffy Sorry, perhaps I wasn't clear in the original question, my system does call the function, but crashes/exits/closes when it completes the function. I do not want this to happen. – Lyra Orwell Mar 16 '19 at 15:46
  • BTW, if you want to track what is and isn't run, a good place to start is the [trace module](https://docs.python.org/2/library/trace.html). – Charles Duffy Mar 16 '19 at 15:47
  • @LyraOrwell, ...what do you want it to do instead of exiting? Run the function *again*? Do something else? Do you have code that's intended to make it do that other thing? [Edit] the question to show us that code! – Charles Duffy Mar 16 '19 at 15:47
  • you can add statements like `print('Job starts/ends....')` at the beginning/end of the function to check if it's actually triggered – PRMoureu Mar 16 '19 at 15:51
  • If what you want it to do is drop to a Python REPL, running it with `python -i yourscript.py` or making the shebang `#!/usr/bin/python -i` (on a UNIXlike platform where shebangs are honored; YMMV if you have an IDE doing the invocation) will do that. – Charles Duffy Mar 16 '19 at 15:51
  • That isn't a crash. Also, please read [mre]. – Karl Knechtel Oct 01 '22 at 18:28

0 Answers0