4 Replies - 722 Views - Last Post: 26 March 2014 - 07:41 AM Rate Topic: ***-- 2 Votes

#1 al.25  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-March 14

Bluescreening : what's wrong with my code?

Posted 26 March 2014 - 03:19 AM

Hello, for an assignment I basically have to create a to-do list which accepts various commands which works off a textfile.

However, I'm getting random blue screens and I'm not sure why I get them. They seem to occur randomly, either after I try to do one thing or when I close the window. I can't seem to pinpoint the particular cause because it's been inconsistent where a crash occurs. So I post here seeking for advice on my code and possible reasons why. I guess as a side-interest, what particular things do evil to the computer/Python (bad coding practices that could lead to crashes) as well.

I'm also new to Python so bear with my crappy coding, thanks. Below at the end is the coding I've done. I've fulfilled the assignment requirements, everything is functional and works. The only issue is the random crashing which I can't understand why.

One requirement was for the parse_command function, where I have to return the results in the way I have (a pair consisting of command name and the list of arguments for the command, and (None, None) when the command is invalid).

Some parts of the code were given to me by the teacher to help us out, but I doubt they're the problem.

The textfile contains basic stuff such as:
test task, 26/03/2014
test task 2, 27/03/2014
test task 3, 29/03/2014
test task 4, 22/04/2014
test task 5, 26/04/2014


Also, I'm having doubts on my interact function:

def interact():
    p = parse_command(raw_input("What would you like to do? "))
    if p != ("q", ()):
        interact()


Previously, I had the interact() get called within the parse_command function itself when I wanted to keep prompting the user for an input, but when I closed the program it would bluescreen SOMETIMES. I noticed then that all the results of parse_command get returned when it ends.

#********************************************
# This part can't be modified:
import datetime

DATE_FORMAT = '%d/%m/%Y'
TODAY = datetime.datetime.today()
NEXT_WEEK = TODAY + datetime.timedelta(days=7)

def as_datetime(date_string):
    try:
        return datetime.datetime.strptime(date_string, DATE_FORMAT)
    except ValueError:
        # The date string was invalid
        return None

def as_date_string(date):
    return date.strftime(DATE_FORMAT)

# End of no modifier
#********************************************

# MY OWN CODE

def load_list(filename):
    """ 

    load_list(filename) -> list
    """
    output = [] # empty list

    # Open file for reading
    f = open(filename, 'rU')

    # Loop through file contents
    for line in f:
        s = line.partition(',')
 
        task = s[0]
        date = s[2] #extends to new line as well... '25/04/2014
                    #                               '1234567890
        output.append((as_datetime(date[:10]), task))
    f.close()
    return output

def save_list(todolist, filename):
    """

    save_list(list, str)"""
    fOut = open(filename, 'w')

    for d, t in todolist:
        
        fOut.write(t + "," + as_date_string(d) + "\n")

    fOut.close()

def display(todolist, show_all):
    """

    display(list, boolean)"""
    todolist.sort()
    if show_all:
        for d, t in todolist:
            print as_date_string(d) + ": " + t
    else:
        for d, t in todolist:
            if (d - TODAY).days >= 0 and (d - TODAY).days < 7:
                print as_date_string(d) + ": " + t

def add_item(todolist, name):
    """ Add an item to the list in format: <date>, <task>

    add_item(list, str) -> """

    s = name.split(',')
    date = as_datetime(s[1].strip())
    task = s[0].strip()

    todolist.append((date, task))
    


def remove_item(todolist, name):
    """ Remove item from the list of task <name>.

    remove_item(list, str) -> boolean"""

    # What if there is duplicate task names?
    # Current method removes the first.

    name = name.strip()
    i = 0
    for d, t in todolist:
        if t == name:
            todolist.pop(i)
            return True
        i += 1
    return False
 
def parse_command(command):
    """
    all on - display all items
    all off - display all items due within 7 days
    q

    rm something
    add name, 11/11/2014

    parse_command(str) -> tuple"""
    
    """command_base = command.partition(" ")[0]
    args = command.partition(" ")[2]
    print command_base + " " + args"""

    todo = load_list('todo.txt')

    # 'q'uit:
    # - terminates program.
    if command == "q":
        save_list(todo, 'todo.txt')
        return ("q", ())

    # 'all on':
    # - displays all tasks due
    elif command == "all on":
        display(todo, True)
        return ("all", "on")

    # 'all off'
    # - displays only tasks due within 7 days, excluding today
    elif command == "all off":
        display(todo, False)
        return ("all", "off")

    # 'rm <task>':
    # - Removes <task> from the list of tasks. Requires matching input.
    elif "rm " in command:
        task = command.split(" ", 1)[1] # .strip() #.strip() removes unnecessary whitespace, but should it be user-error?
        if remove_item(todo, task):
            print "'" + task + "' was removed from the list."
        else: # Output error message with input exactly as user inputs it.
            print "ERROR: Could not find the task '" + command.split(" ", 1)[1] + "' to remove."
        save_list(todo, 'todo.txt')
        return ("rm", task)

    # 'add <task>,<date>':
    # - Requires command to contain both 'add ' and a comma.
    elif "add " in command:
        if not "," in command:
            print "ERROR: Task was input wrong. Use the format 'add <task>,<date>' e.g. 'add apply for extension, 24/09/2015'"
            return (None, None)
        
        add_item(todo, command[4: ])
        date = as_datetime(command[4: ][1].strip())
        task = command[4: ][0].strip()
        save_list(todo, 'todo.txt')
        
        return ("add", (task, date))
    else:
        print "ERROR: Command is not recognised. Please try again."
        return (None, None)
    
def interact():
    p = parse_command(raw_input("What would you like to do? "))
    if p != ("q", ()):
        interact()

#********************************************
# This part can't be modified:
if __name__ == '__main__':
    interact()


Is This A Good Question/Topic? 0
  • +

Replies To: Bluescreening : what's wrong with my code?

#2 MentalFloss  Icon User is offline

  • .
  • member icon

Reputation: 577
  • View blog
  • Posts: 1,500
  • Joined: 02-September 09

Re: Bluescreening : what's wrong with my code?

Posted 26 March 2014 - 05:31 AM

def interact():
    p = parse_command(raw_input("What would you like to do? "))
    if p != ("q", ()):
        interact()



This is called recursion. You shouldn't do this like that because you just go deeper and deeper into the framestack. If you must, use return on the call. However, the best thing to do is to have a looping mechanism like so:

def interact():
    p = ''
    while p not in ('q', ()):
        p = parse_command(raw_input("What would you like to do? "))



I don't think this would have caused a bluescreen but maybe? Fix it and see.

Also, what is this part?: ()

I have not seen such a thing before.
Was This Post Helpful? 1
  • +
  • -

#3 jon.kiparsky  Icon User is offline

  • Beginner
  • member icon


Reputation: 11022
  • View blog
  • Posts: 18,805
  • Joined: 19-March 11

Re: Bluescreening : what's wrong with my code?

Posted 26 March 2014 - 07:11 AM

() defines an empty tuple.


There's a bit of a logic fail here

def interact():
    p = ''
    while p not in ('q', ()):
        p = parse_command(raw_input("What would you like to do? "))



parse_command does not ever return a value that could be found in that list, since that list contains a character and an empty tuple, and parse_command always returns a tuple of the form (char, tup).
>>> q_and_null = ('q',())
>>> q_and_null in q_and_null

Was This Post Helpful? 1
  • +
  • -

#4 MentalFloss  Icon User is offline

  • .
  • member icon

Reputation: 577
  • View blog
  • Posts: 1,500
  • Joined: 02-September 09

Re: Bluescreening : what's wrong with my code?

Posted 26 March 2014 - 07:38 AM

Oh OK. So it should be != then I would suppose.

    # 'q'uit:
    # - terminates program.
    if command == "q":
        save_list(todo, 'todo.txt')
        return ("q", ())



Sorry about that. The while loop should still work:

def interact():
    p = None
    while p != ('q', ()):
        p = parse_command(raw_input("What would you like to do? "))



Here's my mockup:

def parse_command(command):
    if command == 'quit':
        return ('q',())

def interact():
    p = None
    while p != ('q', ()):
        p = parse_command(raw_input("What would you like to do? "))
        
interact()



output said:

What would you like to do? run
What would you like to do? jump
What would you like to do? play
What would you like to do? quit


------------------
(program exited with code: 0)

Was This Post Helpful? 1
  • +
  • -

#5 jon.kiparsky  Icon User is offline

  • Beginner
  • member icon


Reputation: 11022
  • View blog
  • Posts: 18,805
  • Joined: 19-March 11

Re: Bluescreening : what's wrong with my code?

Posted 26 March 2014 - 07:41 AM

Yep, that looks like a reasonable sketch. al.25, go thou and do likewise.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1