2013-01-04 2 views
0

가이아, belwo 코드에서 다음 오류가 발생합니다. 어디에서 ti가 잘못됩니까? 어떤 정리 제안도UnboundLocalError : 할당 전에 참조 된 로컬 변수 'file'

for line in file(timedir + "/change_authors.txt"): 
UnboundLocalError: local variable 'file' referenced before assignment 

코드 아래에 접수 :

import os,datetime 
    import subprocess 
    from subprocess import check_call,Popen, PIPE 
    from shutil import copyfile,copy 

def main(): 
    #check_call("ssh -p 29418 review-droid.comp.com change query --commit-message status:open project:platform/vendor/qcom-proprietary/radio branch:master | grep -Po '(?<=(email|umber):)\S+' | xargs -n2") 
    global timedir 
    change=147441 
    timedir=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') 
    #changeauthors = dict((int(x.split('/')[3]), x) for line in file(timedir + "/change_authors.txt")) 
    for line in file(timedir + "/change_authors.txt"): 
     changeauthors = dict(line.split()[0], line.split()[1]) 
    print changeauthors[change] 
    try: 
     os.makedirs(timedir) 
    except OSError, e: 
     if e.errno != 17: 
      raise # This was not a "directory exist" error.. 
    with open(timedir + "/change_authors.txt", "wb") as file: 
     check_call("ssh -p 29418 review-droid.comp.com " 
      "change query --commit-message " 
      "status:open project:platform/vendor/qcom-proprietary/radio branch:master |" 
      "grep -Po '(?<=(email|umber):)\S+' |" 
      "xargs -n2", 
       shell=True, # need shell due to the pipes 
       stdout=file) # redirect to a file 

if __name__ == '__main__': 
    main() 

답변

1

file()을 사용하여 파일 시스템의 파일을 열지 마십시오. 오류가 발생한 줄에 open을 사용하십시오.


문서 recommends against it : 또한

Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

New in version 2.2.

, 파이썬 3에서 떨어진거야

+0

감사합니다, 뭔가 잘못되었습니다 gerritauthors = dict (line.split() [0], line.split() [1]) .. 기본적으로 공간을 기준으로 각 라인을 분할하고 첫 번째 문자열을 색인으로, 두 번째 문자열을 요소로 ... – user1927396

+0

@ user1927396 You 이를 달성하기 위해'index, element = line.split ('', 1)'을 할 수있다. –

+0

내가 계속 그렇게한다면 TypeError : dict는 최대 1 개의 인수를 필요로하고, 2는 줄에 놓는다. changeauthors = dict (index, element) – user1927396

3

이 기능 범위로 할 것입니다. 주 함수가 나중에 자체 파일 변수를 정의하면 내장 파일 함수가 파손됩니다. 따라서 처음에 호출하려고 할 때 로컬 파일 변수를 자체 예약 했으므로이 오류가 발생합니다. 이 코드를 주 함수에서 제거하거나 나중에 open() 문에서 'file'에 대한 참조를 변경하면 작동합니다. 나는 다음을 수행 할 것입니다 그러나

...

대신 :

for line in file(timedir + "/change_authors.txt"): 

당신은 사용해야합니다

for line in open(timedir + "/change_authors.txt", 'r'): 

open() function 파일 객체를 반환하는 데 사용하고있다한다 file()보다 바람직합니다.

+0

는 실제로 파일, 내가 어디 라인에 대한 스크립트를 가지고, 그 전에 일하는 방법을 잘 모릅니다 덕분에, 파일에있는 – user1927396

관련 문제