我试图让一个函数在用户给定的某个时间在 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 脚本在给定时间运行并处理函数?
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 withselected_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:
where
some_duration
is a float, meant in seconds.Could you please check if this works now?