私は、ユーザから与えられた特定の時間に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スクリプトを実行しておき、指定された時間に関数を処理するにはどうすればよいですか?
コードを更新してくれました。また、@alexandru Plugaruのコード提案を使用しましたが、正しく出力されませんでした。process()は実行されません。 – Brian
'終わり近くに 'time'と' selected_time'があります。あなたがしなければならないことは、デルタとの比較です: 'if selected_time> = current_time> = selected_time + delta'それ以外の場合、あなたの予定された時間を回るかもしれません。二番目の言い分では、 'time'はモジュールであり、現在の時刻ではないので、あなたの比較はうまくいかないでしょう! –
@Brian、Alexandruにあなたの質問に答えられないので、私はここに答えます。問題は、 'selected_time'と現在の時刻との間に等しいと予想されることです。あなたの待っている時間が5秒単位であるため、これは起こりそうにありません。あなたの比較で 'expected_time'の周りにいくらかのマージンを取るべきです(上記の私のコメントを見てください)。 –