输入时间并将其与用户输入进行比较

我试图让一个函数在用户给定的某个时间在 Python 脚本中运行。为此,我使用了 datetime 模块。

到目前为止,这是代码的一部分:

import os
import subprocess
import shutil
import datetime
import time

def process():

    path = os.getcwd()
    outdir = os.getcwd() + 'Output'

    if not os.path.exists(outdir):
        os.mkdir(outdir, 0777)

    for (root, dirs, files) in os.walk(path):
        filesArr = []
        dirname = os.path.basename(root)
        parent_dir = os.path.basename(path)

        if parent_dir == dirname:
            outfile = os.path.join(outdir,  ' ' + dirname + '.pdf')
        else:
            outfile = os.path.join(outdir, parent_dir + ' ' + dirname + '.pdf')

        print " "
        print 'Processing: ' + path

        for filename in files:
            if root == outdir:
                continue
            if filename.endswith('.pdf'):
                full_name = os.path.join(root, filename)
                if full_name != outfile:
                    filesArr.append('"' + full_name + '"')

        if filesArr:
            cmd = 'pdftk ' + ' '.join(filesArr) + ' cat output "' + outfile + '"'
            print " "
            print 'Merging: ' + str(filesArr)

            print " "

            sp = subprocess.Popen(cmd)

            print "Finished merging documents successfully."

            sp.wait()

    return

now = datetime.datetime.now()
hour = str(now.hour)
minute = str(now.minute)
seconds = str(now.second)
time_1 = hour + ":" + minute + ":" + seconds

print "Current time is: "  + time_1

while True:
     time_input = raw_input("Please enter the time in HH:MM:SS format: ")

     try:
        selected_time = time.strptime(time_input, "%H:%M:%S")
        print "Time selected: " + str(selected_time)

        while True:
            if (selected_time == time.localtime()):
             print "Beginning merging process..."
             process()
             break
             time.sleep(5)

        break

     except ValueError:
        print "The time you entered is incorrect. Try again."

问题是试图找到一种方法来比较用户输入的时间与当前时间(如脚本运行时的当前时间)。另外,如何保持 python 脚本在给定时间运行并处理函数?

stack overflow Inputting the time and comparing it with user input
原文答案

答案:

作者头像

I can see various things to be commented in the code you propose, but main one is on selected_time = selected_hour + ..., because I think you are adding integers with different units. You should maybe start with selected_time = selected_hour * 3600 + ....

Second one is when you try to check the validity of the inputs: you make a while on a check that cannot evolve, as user is not requested to enter another value. Which means these loops will never end.

Then, something about robustness: maybe you should compare the selected time to the current time by something more flexible, i.e. replacing == by >= or with some delta.

Last thing, you can make the Python script wait with the following command:

import time
time.sleep(some_duration)

where some_duration is a float, meant in seconds.

Could you please check if this works now?

作者头像

First of all I'd suggest you look at: http://docs.python.org/library/time.html#time.strptime which might prove to be helpful in your situation when trying to validate the time.

You can something like this: import time

import time

while True: #Infinite loop        
    time_input = raw_input("Please enter the time in HH:MM:SS format: ")
    try:
        current_date = time.strftime("%Y %m %d")
        my_time = time.strptime("%s %s" % (current_date, time_input),
                             "%Y %m %d  %H:%M:%S")
        break #this will stop the loop
    except ValueError:
        print "The time you entered is incorrect. Try again."

Now you can do stuff with my_time like comparing it: my_time == time.localtime()

The simplest way to make the program running until 'it's time is up' is as follows:

import time

while True:
    if (my_time <= time.localtime()):
        print "Running process"
        process()
        break
    time.sleep(1) #Sleep for 1 second

The above example is by no means the best solution, but in my opinion the easiest to implement.

Also I'd suggest you use http://docs.python.org/library/subprocess.html#subprocess.check_call to execute commands whenever possible.