2014-11-15 3 views
-3

나는 모든 비디오 파일을 디렉토리에 나열하고 사용자 입력에 따라 재생할 수있는 간단한 파이썬 프로그램을 작성하고 있습니다. 그러나이 코드를 실행하는 동안 범위를 벗어난 목록 오류가 발생합니다.파이썬 코드에서 범위를 벗어난 오류 목록 표시

코드 :

import os 

from subprocess import Popen 

def processFile(currentDir): 
    # Get the absolute path of the currentDir parameter 
    currentDir = os.path.abspath(currentDir)           
    global list 
    list=[] 

    filesInCurDir = os.listdir(currentDir) 

    # Traverse through all files 
    for file in filesInCurDir: 
     curFile = os.path.join(currentDir, file) 

     # Check if it's a normal file or directory 
     if os.path.isfile(curFile): 
      # Get the file extension 
      curFileExtension = curFile[-3:] 

      # Check if the file has an extension of typical video files 
      if curFileExtension in ['avi', 'dat', 'mp4', 'mkv', 'vob']: 
       # We have got a video file! Increment the counter 
       processFile.counter += 1 
       list.append('curFile') 

       # Print it's name 
       print(processFile.counter, file) 
     else: 
      # We got a directory, enter into it for further processing 
      processFile(curFile) 
if __name__ == '__main__': 
    # Get the current working directory 
    currentDir = os.getcwd() 

    print('Starting processing in %s' % currentDir) 

    # Set the number of processed files equal to zero 
    processFile.counter = 0 

    # Start Processing 
    processFile(currentDir) 

    # We are done. Exit now. 
    print('\n -- %s Movie File(s) found in directory %s --' \ 
      % (processFile.counter, currentDir)) 
    print('Enter the file you want to play') 
    x = int(input()) 
    path = list[x-1] 
    oxmp=Popen(['omxplayer',path]) 
+2

범위를 벗어난 라인은 무엇입니까? – Crummy

+2

@Crummy : 두 번째 줄부터 마지막 ​​줄까지 오류가 발생할 가능성이있는 것처럼 보입니다. 비 슬라이스 목록 색인이있는 유일한 줄입니다. 이 문제는 아마도 입력 프롬프트에 대한 응답으로 1 ... processFile.counter 범위에없는 숫자를 입력하는 것과 관련이 있습니다. –

+1

'list'는 파이썬에서 예약어입니다. 물론 변수 이름을 사용할 수는 있지만 내장 마스크를 사용하지 마십시오. – Anthon

답변

1

아하, 당신의 문제를 발견했다. processFile에서

, 당신이 당신이 재귀 때마다, 다시 목록을 삭제하는 것을 의미

def processFile(currentDir): 
    # ... 
    global list 
    list=[] 
    # ... 
    processFile(...) 

말! 즉, processFile.counter 숫자가 실제 길이 목록과 비 동기화됩니다. 이에

세 노트 : processFile.counter 같은 함수에

  • 저장 변수는 일반적으로 AFAIK, 눈살을 찌푸리게한다.
  • 별도의 카운터가 필요 없습니다. len(list)을 입력하여 목록에있는 항목 수를 찾을 수 있습니다.
  • 목록 문제 자체를 수정하려면 함수 외부에서 목록 변수를 초기화하거나 수정할 매개 변수로 전달하는 것이 좋습니다.
+0

감사합니다. 바보 같은 실수를했습니다. –

+2

대답이 문제를 해결한다면 아마도이를 수락할까요? –

관련 문제