2011-08-12 20 views
1

私は、ユーザから与えられた特定の時間に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スクリプトを実行しておき、指定された時間に関数を処理するにはどうすればよいですか?

答えて

0

あなたが提案したコードではコメントされるべきことがたくさんありますが、主なものはselected_time = selected_hour + ...です。異なる単位で整数を追加していると思います。おそらくselected_time = selected_hour * 3600 + ...で始めるべきです。

入力の妥当性をチェックしようとしています。whileは、ユーザが別の値を入力する必要がないため、進化できないチェックで行います。つまり、これらのループは決して終わらないでしょう。

次に、堅牢性については、を>=で置き換えるか、デルタで置き換えるなど、選択した時刻と現在の時刻を比較する必要があります。

最後のものは、Pythonスクリプトは、次のコマンドを使用して待つことができます:some_durationは秒単位で意味フロート、ある

import time 
time.sleep(some_duration) 

これが今動作しているかどうか確認してください。

+0

コードを更新してくれました。また、@alexandru Plugaruのコード提案を使用しましたが、正しく出力されませんでした。process()は実行されません。 – Brian

+0

'終わり近くに 'time'と' selected_time'があります。あなたがしなければならないことは、デルタとの比較です: 'if selected_time> = current_time> = selected_time + delta'それ以外の場合、あなたの予定された時間を回るかもしれません。二番目の言い分では、 'time'はモジュールであり、現在の時刻ではないので、あなたの比較はうまくいかないでしょう! –

+0

@Brian、Alexandruにあなたの質問に答えられないので、私はここに答えます。問題は、 'selected_time'と現在の時刻との間に等しいと予想されることです。あなたの待っている時間が5秒単位であるため、これは起こりそうにありません。あなたの比較で 'expected_time'の周りにいくらかのマージンを取るべきです(上記の私のコメントを見てください)。 –

0

まず、私はあなたが見ることをお勧めします: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を使用してコマンドを実行することをお勧めします。

+0

あなたのコードを試しているときに私はこのエラーが発生しています: 'AttributeError: 'str'オブジェクトに属性 'strptime''がありません – Brian

+0

問題はありました。主な質問のコードを更新しました。それは時間が正しく出力されず、プロセスは実行されませんが、そのように機能します。 – Brian

+0

問題は 'if(selected_time == time):' 'time.struct_time'オブジェクトである' selected_time'変数を 'time'モジュールと比較しています。代わりに 'if(selected_time == time.localtime())'を実行する必要があります。 –

関連する問題