2011-08-12 4 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." 

문제에서와 같이 (현재 시간을 현재 시간과 사용자 입력 시간을 비교하는 방법에 대한 방법을 찾기 위해 노력하고있다 필요하다 스크립트가 실행 중일 때). 또한, 어떻게 파이썬 스크립트를 실행하고 주어진 시간에 함수를 처리합니까?

답변

0

내가 제안한 코드에서 주석을 달 수있는 여러 가지 사항을 볼 수 있지만, 기본 단위는 selected_time = selected_hour + ...입니다. 다른 단위로 정수를 추가한다고 생각하기 때문입니다. 아마도 selected_time = selected_hour * 3600 + ...으로 시작해야합니다.

두 번째는 입력 값의 유효성을 검사하는 경우입니다. 사용자가 다른 값을 입력하도록 요구하지 않으므로 진화 할 수없는 검사에서 while을 확인하십시오. 이 루프가 끝나지 않을 것임을 의미합니다.

다음은 견고성에 대해 설명합니다. 선택한 시간과 현재 시간을 더 유연하게 비교해야합니다 (예 : ==>= 또는 일부 델타로 교체해야 함).

마지막 것은, 당신은 파이썬 스크립트는 다음 명령을 기다리게 할 수 있습니다 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' 그렇지 않으면 당신의 예정된 시간을 돌아 다닐 수 있습니다. 둘째, '시간'은 현재의 시간이 아닌 모듈이며, 비교가되지 않습니다. –

+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())을 실행해야합니다. 예제를 더 잘 작성해야합니다. –