Inputting the time and comparing it with user input
I'm trying to make a function run within a Python script at a certain time given by the user. To do this I'm using the datetime module.
This is part of the code so far:
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 + ":" + min开发者_Go百科ute + ":" + 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."
The problem is having is trying to find a way on how to compare the user inputted time with the current time (as in, the current time for when the script is running). Also, how do I keep a python script running and process a function at the given time?
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.
精彩评论