输入时间并与用户输入比较
我正在尝试在一个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脚本持续运行,并在指定的时间处理一个函数呢?
2 个回答
首先,我建议你看看这个链接:http://docs.python.org/library/time.html#time.strptime,它可能会在你验证时间的时候对你有帮助。
你可以这样做:
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."
现在你可以用 my_time
做一些事情,比如比较时间:my_time == time.localtime()
让程序一直运行直到“时间到了”的最简单方法如下:
import time
while True:
if (my_time <= time.localtime()):
print "Running process"
process()
break
time.sleep(1) #Sleep for 1 second
上面的例子并不是最好的解决方案,但在我看来是最容易实现的。
另外,我建议你在可能的情况下使用 http://docs.python.org/library/subprocess.html#subprocess.check_call 来执行命令。
我看到你代码里有很多地方可以评论,但最主要的是在 selected_time = selected_hour + ...
这一行,因为你可能是在加不同单位的整数。你应该先把它改成 selected_time = selected_hour * 3600 + ...
。
第二个问题是你在检查输入有效性时:你用 while
循环去检查一个不会变化的条件,因为用户没有被要求输入其他值。这意味着这个循环永远不会结束。
然后,有关代码的健壮性:你可能应该用更灵活的方式来比较选定的时间和当前时间,比如把 ==
改成 >=
或者加上一个小的误差值。
最后,你可以用下面的命令让 Python 脚本暂停:
import time
time.sleep(some_duration)
这里的 some_duration
是一个浮点数,表示秒数。
你能检查一下现在是否能正常工作吗?