• Revista PROGRAMAR: Já está disponível a edição #53 da revista programar. Faz já o download aqui!

rolando2424

[Python] Agenda diária

6 mensagens neste tópico

Bem, isto já devia ter estado feito já faz tempo (e tecnicamente já está feito à tempos...), mas prontos :D

Isto é um pequeno script, que quando executado sem nenhuma flag, vai buscar a um ficheiro de texto, as coisas que estão lá marcadas para o dia corrente.

Para aceder à interface, é só usar a flag -i ou --interface.

O ficheiro a ser usado tem de estar na mesma pasta que o ficheiro de script (por enquanto :D)

Por exemplo, coloquem o script em ~/.time_table e o ficheiro de agenda será criado lá.

Eu criei este script com a ideia de fazer com que ele seja colocado no ~/.bash_profile (no exemplo anterior, teriam que colocar no bash_profile, a linha ~/.time_table/nome_do_ficheiro.py ) para ele ser executado sempre que abrir uma shell de bash.

Mas podem sempre usa-lo de outras maneiras :D

EDIT: Pelos vistos o ficheiro da agenda tem que ficar no ~, caso queiram colocar o script no .bash_profile

O ficheiro da agenda terá o seguinte formato:

dia

coisa1

coisa2

coisaN

dia2

coisa1

coisa2

coisaN

Um exemplo:

2007/07/31

Get up

Survive

Go to bed

2007/08/22

Sucess

Isto significa que deve

De estar a trabalhar bem

Vejam os comments (vejam também a chart, e sigam as setas ( < > ^ v ) para saberem como o programa "flui") para perceberem melhor.

Exemplo: menu --- (como iniciaram com a flag -i) ---> interface ----> add_something ---> check_date ---> interface ---> remove_something ---> exit (que não está no chart, mas prontos.

EDIT: Vou só colocar aqui o flow chart em Monospace, porque o GeSHi coloca os comments em itálico, e depois não se percebe nada no chart :D (e porque acho que em Monospace fica mais bonito.

Flow of the program

(in function)

/---<--<-\

/---pretty_print / \

^ v \

/ / /----add_something

menu--- / / \ /

\ v ^ v ^

v command -i / / \ /

\------------interface-( check_date

\ \ / \

^ v ^ v

\ \ / \

^ \----remove_something

\ /

\--<--<---/

E sem mais demoras, o script :

#!/usr/bin/env python

# Created by Rolando2424 (Released in 2007/08/28)

# Use it, custom it, change it, love it, worship it

#
#  Flow of the program
#  (in function)
#
#                                  /---<--<-\                 
#           /---pretty_print      /          \   
#          ^                     v            \           
#         /                     /      /----add_something
#  menu---                     /      /      \      /   
#         \                   v      ^        v    ^   
#          v  command -i     /      /          \  /
#           \------------interface-(           check_date
#                            \      \           /   \
#                             ^      v         ^     v
#                              \      \       /       \
#                               ^      \----remove_something
#                                \           /
#                                 \--<--<---/
#

import sys
import time
import os
import re
import string

# First, let's get todays date.
time_now = time.localtime()
today = ["%s" % time_now.tm_year,
   "%s" % time_now.tm_mon,
   "%s" % time_now.tm_mday]

if len(today[1]) < 2: # To avoid things like 2007/4/3
   today[1] = "0" + today[1]

if len(today[2]) < 2: # Same thing, but for the day
   today[2] = "0" + today[2]

str_today = "/".join(today) # Now we have todays date 

agenda = {} # Will hold the thing that exist in the file.
           # The format is: {day : list_with_all_things_for_that_day}

def pretty_print():
   "Prints the things to do in a pretty and nice way"

   print "Today is: %s" % str_today

   if str_today in agenda:
       print "Things to do today:"
       print ""
       print "\n".join(agenda[str_today])
       print ""

   else:
       print "You've got nothing to do today."
       print ""


def check_date(date):
   "Return date if date passes all the tests, otherwise return 1"

   try:
       if len(date.split(date[4])[1]) != 2:
           temp_date = date.split(date[4])
           temp_date[1] = "0" + temp_date[1]
           date = "/".join(temp_date)

       if len(date.split(date[4])[2]) != 2:
           temp_date = date.split(date[4])
           temp_date[2] = "0" + temp_date[2]
           date = "/".join(temp_date)

   except IndexError:
       print "Date is not valid, please try again."
       print ""
       return 1

   # Insert regex to verify the date
   pattern_of_date = re.compile(r"""
   ^       # Beginning of the string
   (\d{4}) # Match any four numbers (The year)
   ([/|-]) # A separator (either / or - )
   (\d{2}) # Match any two numbers (The month)
   ([/|-]) # A separator (either / or - )
   (\d{2}) # Match any two numbers (The day)
   $       # End of string""", re.VERBOSE)

   # But it still allows the use of the day 31 in a 30 day month
   # ^ Fixed, but in a ugly way (work that out later)
   if re.search(pattern_of_date, date) == None \
           or int(date.split(date[4])[1]) not in range(1, 13) \
           or int(date.split(date[4])[2]) not in range(1, 32) \
           or date[-5:] in ("04/31", "04-31", \
               "06/31", "06-31", \
               "09/31", "09-31", \
               "11/31", "11-31"):
       print "Date is not valid, please try again."
       print ""
       return 1

   # Easter Egg and lame attempt at a joke ^_^
   if date[-5:] in ("02/30", "02-30", "02/31", "02-31"):
       print "Did you know I was born that day?"
       print ""
       return 1

   return date


def add_something():
   "To add something to a given day"

   global agenda
   print "To what day do you want to add? [YYYY/MM/DD]"
   day = raw_input()

   date_pass = check_date(day)

   if date_pass == 1:
       add_something()

   else: #If it's not 1, then it's the parsed date
       day = date_pass

   print "What do you have to do for that day?"
   stuff_to_do = raw_input()

   try:
       agenda[day].append(stuff_to_do)

   except KeyError:
       agenda[day] = [stuff_to_do]


   def add_something_to_the_same_day():
       print "What else to you want do add?"
       stuff_to_do = raw_input()

       try:
           agenda[day].append(stuff_to_do)
       except KeyError:
           agenda[day] = [stuff_to_do]


   print "Do you want to add another thing to this day?"

   yes_no = ""
   yes_no = raw_input("[ yes / no ] ")

   if yes_no.lower() in ("y", "yes"):
       add_something_to_the_same_day()

   else:
       pass

   print "Do you want to exit the program?"
   exit = raw_input("[ yes / no ] ")

   if exit.lower() in ("y", "yes"):
       print "Good Bye."
       print ""
       file_writer()
       sys.exit()

   else:
       interface()


def remove_something():
   "To remove something to a given day"

   global agenda
   print "To what day do you want to remove something? [YYYY/MM/DD]"
   day = raw_input()

   date_passed = check_date(day)

   if date_passed == 1:
       remove_something()

   try:

       for i in range(0, len(agenda[day])):
           print "%s ---> %s" % (i, agenda[day][i])

       print "Type the number of the thing you want to remove:"
       print "[0 - %s]" % (len(agenda[day])-1),

       try:
           number_to_remove = int(raw_input())

       except ValueError:
           print "You have to time a number."
           remove_something()

       print "Going to remove: %s" % (agenda[day][number_to_remove])
       print "Confirm: [Y / N]",
       yes_no = raw_input()

       if yes_no.lower() in ("y", "yes"):
           pass

       if yes_no.lower() in ("n", "no"):
           print "Ok, returning to the menu."
           interface()

       agenda[day].remove(agenda[day][number_to_remove])

   except KeyError:
       print "Sorry, you have nothing planned on that day."

   print "Do you want to exit the program?"
   exit = raw_input("[ yes / no ] ")

   if exit.lower() in ("y", "yes"):
       print "Good Bye."
       print ""
       file_writer()
       sys.exit()

   else:
       interface()


def argv_parser():
   """Parses the arguments passed at runtime.

   Currently it doesn't do much,
   but I hope to change that in the future."""

   argv = sys.argv[1:] # No need to have the name of the script

   for argument in argv:

       if argument in ("-i", "--interface"):
           open_interface = 1

       else:
           print "Currently there is only one option:"
           print "-i or --interface opens the interface to the program."
           print
           sys.exit()

   if open_interface == 1:
       interface()

   else:
       pass


def interface():
   "Command Line Interface"

   print ""
   print "Welcome. What do you want to do today?"
   print
   print "1) Add something to to a day?"
   print "2) Remove something to a day?"
   print "3) Exit"
   choice = 0

   try:
       choice = int(raw_input("[1, 2, 3] "))

   except ValueError:
       print "Command Unknown. Please try again"
       interface()

   if choice == 1:
       add_something()

   elif choice == 2:
       remove_something()

   elif choice == 3:
       print "Good Bye."
       print
       file_writer()
       sys.exit()

   else:
       print "Unknown option, please try again."
       interface()


def file_reader(filename):
   "Reads the file that has the agenda."

   global agenda

   pattern = re.compile(r"""
   (           # Begin to memorize the date
   \d{4}       # Search for 4 numbers
   [\|/|-]     # One separator (either \ / or -)
   \d{2}       # Search for 2 numbers
   [\|/|-]     # One separator (either \ / or -)
   \d{2}       # Searcg for 2 numbers
   )           # Finish memorizing
   (\D+)       # Memorize one or more group of non-numbers
   """, re.VERBOSE)

   file_to_read = os.path.join(file(filename, "r"))
   str_content_file = file_to_read.read()

   text_found = re.findall(pattern, str_content_file)

   for content in range(0, len(text_found)):
       agenda[text_found[content][0]] = text_found[content][1]

   for day in agenda:
       agenda[day] = agenda[day].splitlines()

       if agenda[day][1] == "":
           agenda[day] = agenda[day][1:]

       if agenda[day][-1] == "":
           agenda[day] = agenda[day][:-1]

       for stuff in agenda[day]:

           if stuff == "":
               agenda[day].remove("")

           else:
               pass

def file_writer():
   """Writes the agenda to the file time_table.txt

   The format of writing is:
   newline
   day
   newline
   thing1
   thing2
   thingN
   newline"""

   global agenda
   file_to_save = os.path.join(file("time_table.txt", "w"))
   for day in agenda:
       file_to_save.write("%s\n" % day)
       file_to_save.write("\n")
       file_to_save.write("%s\n" % "\n".join(agenda[day]))
       file_to_save.write("\n")


def main():
   "This is the first fuction called when running the script"

   file_reader("time_table.txt")

   if len(sys.argv) == 1: # No argument passed (example, execution at the
                          # begin of a bash shell), just print today's
                          # table
       pretty_print()

   else:
       argv_parser()


main()

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

    # Easter Egg and lame attempt at a joke ^_^

    if date[-5:] in ("02/30", "02-30", "02/31", "02-31"):

        print "Did you know I was born that day?"

        print ""

        return 1

No segundo print, não precisas do "" :)

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Não pode usar um \n\n\ ? (pergunta de noob :) )

\n\n\ não, mas \n\n podes :P (não podes ter string com "olasfasdfsadfasfd\", uma vez a barra tá a escapar o ", evitando que feche a string.).
0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

    # Easter Egg and lame attempt at a joke ^_^

    if date[-5:] in ("02/30", "02-30", "02/31", "02-31"):

        print "Did you know I was born that day?"

        print ""

        return 1

No segundo print, não precisas do "" :P

Eu sei, mas assim fica mais explícito :)

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Não pode usar um \n\n\ ? (pergunta de noob :) )

\n\n\ não, mas \n\n podes :P (não podes ter string com "olasfasdfsadfasfd\", uma vez a barra tá a escapar o ", evitando que feche a string.).

That's what I meant :P

0

Partilhar esta mensagem


Link para a mensagem
Partilhar noutros sites

Crie uma conta ou ligue-se para comentar

Só membros podem comentar

Criar nova conta

Registe para ter uma conta na nossa comunidade. É fácil!


Registar nova conta

Entra

Já tem conta? Inicie sessão aqui.


Entrar Agora