我试图让一个函数在用户指定的特定时间在 Python 脚本中运行。为此,我使用日期时间模块。
这是迄今为止代码的一部分:
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 脚本运行并在给定时间处理函数?
我可以在您提出的代码中看到要注释的各种内容,但主要的一个是在
selected_time = selected_hour + ...
上,因为我认为您正在添加具有不同单位的整数。你也许应该从 selected_time = selected_hour * 3600 + ...
开始。
第二个是当您尝试检查输入的有效性时:您在无法进化的检查上做出
while
,因为不要求用户输入另一个值。这意味着这些循环永远不会结束。
然后,关于稳健性:也许您应该通过更灵活的方式将所选时间与当前时间进行比较,即用
==
或一些增量替换 >=
。
最后一件事,您可以使用以下命令让 Python 脚本等待:
import time
time.sleep(some_duration)
其中
some_duration
是浮点数,以秒为单位。
您可以检查一下现在是否有效吗?
首先,我建议您查看:http://docs.python.org/library/time.html#time.strptime 当您尝试验证时间时,这可能会对您的情况有所帮助。
你可以这样: 导入时间
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 来执行命令。