在程序上下文中向日期时间输入添加异常处理的最简单方法是什么?

时间:2019-08-02 22:31:59

标签: python datetime

我想在调用日期后立即验证日期的输入,以使用户不会输入全部三个,然后再次收到错误/提示输入日期的提示,但是我想不出一种方法去做。我是否需要重组,或者有什么方法可以丢失?

我有一个类对象library("shiny") library("dplyr") library("ggplot2") shinyApp( ui = fluidPage( # Layout with sidebar sidebarLayout( ## Sidebar ----- sidebarPanel( # > some example input on sidebar ----- selectInput("choice", "Choose species", choices = c("none", unique(as.character(iris$Species))), selected = "setosa") ), # closes Sidebar-Panel # Main-Panel ------ mainPanel( br(), tabsetPanel( # > Plot ------- tabPanel("Plot tab", value = 1, plotOutput("plot_text") ), # closes tabPanel id = "tabselected", type = "pills" ) # closes tabsetPanel ) # closes mainPanel ) # closes sidebarLayout ), # closes fluidPage # Server ------ server = function(input, output, session){ data_indicator <- reactive({ validate( need(input$choice %in% iris$Species, "No plot available for chosen filter criteria!") ) iris %>% mutate(Species = as.character(Species)) %>% filter(Species == input$choice) }) output$plot_text <- renderPlot({ # Alternativly use validate here in the following way: # validate( # need(input$choice %in% data_indicator()$Species, "No plot available for chosen filter criteria!") # ) ggplot(data_indicator(), aes(x = Species, y = Sepal.Length)) + geom_col() }) } # Closes server ) # Closes ShinyApp 定义如下:

task

然后通过定义如下的函数class task: def __init__(self, name, due, category): self.name = name self.due = datetime.strptime(due, '%B %d %Y %I:%M%p') self.category = category def expand(self): # returns the contents of the task return str(self.name) + " is due in " + str((self.due - datetime.now())) 创建该类:

addTask

如下收集输入:

def addTask(name, due, category):
    newTask = task(name, due, category)
    data.append(newTask)
    with open('./tasks.txt', 'wb') as file:
        pickle.dump(data, file)
    load_data()
    list_tasks()

1 个答案:

答案 0 :(得分:1)

一种方法是在try / except块中将日期时间传递到addTask之前对其进行验证。

def ask():
    while True:
        arg = input("").lower()
        if arg == "add":
            task = input("What is the task? ")
            due = input("When's it due? ")
            category = input("What's the category? "))
            try:
                due = datetime.strptime(due, '%B %d %Y %I:%M%p')
            except ValueError:
                raise ValueError("Incorrect date format")
            addTask(task, due, category)
        elif arg =="help":
            help()
        elif arg =="list":
            list_tasks()
        else:
            print("Command not recognized. Type 'help' for a list of commands.")

还有更强大的验证方法,例如使用棉花糖库,但这对于您正在研究的内容可能会显得过大。