2014-07-23 1 views
-3

이 프로그램은 스프레드 시트에서 여러 데이터를 가져 와서 줄 단위로 인쇄하도록 설계되었습니다. 코드 :while 문에서 제어 변수를 빼면 Python 프로그램이 충돌 함

import xlrd 
from time import sleep 
password = 0 
username = 0 
book = xlrd.open_workbook("login-book.xlsx") 
print "Testing, now printing the workssheet name", book.sheet_names() 
print "Should say 'main_sheet'" 
sleep(2) 
sh = book.sheet_by_index(0) 
numrows = sh.nrows 
numcollums = sh.ncols 
print "rows", numrows, "columns", numcollums 
print "Cell A1 contains", sh.cell_value(rowx=0, colx=0) 
print "Should say 'HAS ACTIVATED'" 
sleep(2) 
print "beginning...." 
def setlogindata(cell1r, cell1c, cell2r, cell2c): 
    global username 
    global password 
    username = sh.cell_value(rowx=cell1r,colx=cell1c) 
    password = sh.cell_value(rowx=cell2r,colx=cell2c) 
    print username 
    print password 

def writeall(): 
    cell1r = 1 
    cell1c = 1 
    cell2r = 1 
    cell2c = 2 
    while numrows != 0: 
     setlogindata(cell1r, cell1c, cell2r, cell2c) 
     sleep(1) 
     cell1r = cell1r + 1 
     cell2r = cell2r + 1 
     numrows = numrows - 1 

writeall() 
sleep(1000) 

초기에는 의도 한대로, 그 다음 사용자 이름, 그 다음 암호 요법 요법 다음에 사용자 이름, 콘솔에 다음 암호를 인쇄 작동합니다. 그러나이 줄을 제거하면이 방법으로 만 작동합니다.

numrows = numrows - 1 

이 줄이 여기에있는 한, 첫 번째 사용자 이름/암호 집합을 인쇄 한 다음 즉시 충돌합니다. 그러나이 줄이 입력되어 있지 않으면 프로그램에서 인쇄 할 모든 데이터가 포함 된 스프레드 시트의 끝 부분에 도달하는 충돌을 일으 킵니다. 왜 이런 일이 일어나는 지 모르겠다.

+1

어디서 추적합니까? –

+0

오류 보고서를 읽기 전에 창이 닫히는 것을 알 수 없습니다. – user3703570

+0

먼저 개봉을 시도 했습니까? –

답변

0

'UnboundLocalError : 할당 변수 '앞에 참조 된 로컬 변수 'numrows'가 있습니다. 즉, 클로저에서 외부 변수를 사용한다는 의미입니다. 자세한 내용은 link입니다.

당신이해야 할 일은 정말로 간단합니다. 다음과 같이 while 루프 위에 한 줄을 추가하십시오.

... 
global numrows 
while numrows !=0: 
... 
관련 문제