2010-06-02 4 views
3

대학 프로젝트 용으로 자체 수정 코드를 사용하고 있습니다.Python - IDLE을 사용하는 Python 2.5.6에서 코드 스 니펫이 작동하지 않습니다.

는 여기있다 :

import datetime 
import inspect 
import re 
import sys 

def main(): 
    # print the time it is last run 
    lastrun = 'Mon Jun 8 16:31:27 2009' 

    print "This program was last run at ", 
    print lastrun 

    # read in the source code of itself 
    srcfile = inspect.getsourcefile(sys.modules[__name__]) 
    f = open(srcfile, 'r') 
    src = f.read() 
    f.close() 

    # modify the embedded timestamp 
    timestamp = datetime.datetime.ctime(datetime.datetime.now()) 
    match = re.search("lastrun = '(.*)'", src) 
    if match: 
     src = src[:match.start(1)] + timestamp + src[match.end(1):] 

    # write the source code back 
    f = open(srcfile, 'w') 
    f.write(src) 
    f.close() 

if __name__=='__main__': 
    main() 

불행하게도, 그것은 작동하지 않습니다. 오류가 반환되었습니다 :

# This is the script's output 
This program is last run at Mon Jun 8 16:31:27 2009 
# This is the error message 
Traceback (most recent call last): 
    File "C:\Users\Rui Gomes\Desktop\teste.py", line 30, in <module> 
    main() 
    File "C:\Users\Rui Gomes\Desktop\teste.py", line 13, in main 
    srcfile = inspect.getsourcefile(sys.modules[__name__]) 
    File "C:\Python31\lib\inspect.py", line 439, in getsourcefile 
    filename = getfile(object) 
    File "C:\Python31\lib\inspect.py", line 401, in getfile 
    raise TypeError('{!r} is a built-in module'.format(object)) 
TypeError: <module '__main__' (built-in)> is a built-in module 

모든 해결책에 대해 감사드립니다.

+2

자체 수정 코드는 악의적 인 코드입니다. 어떤 언어로. –

+3

IDLE 2.5.6에서 \ Python31 \ lib 리소스를 호출하고 있습니다. 경로를 확인 하시겠습니까? – Don

+0

와우, 그건 나쁜 생각이야. 실행 시간을 다른 곳에서 기록 할 수없는 이유는 무엇입니까? –

답변

4

IDLE을 벗어나서 실행하면 완벽하게 실행되므로 문제는 코드에만있는 것이 아니라 실행중인 환경에서 발생합니다. 당신은 당신이 실제로 ...하는 IDLE 'C:\\Python26\\Lib\\idlelib\\idle.pyw'을 수정하려고

# read in the source code of itself 
srcfile = inspect.getsourcefile(sys.modules[__name__]) 
f = open(srcfile, 'r') 
src = f.read() 
f.close() 

에서 IDLE을 실행하면

>>> import inspect 
>>> sys.modules[__name__] 
<module '__main__' from 'C:\Python26\Lib\idlelib\idle.pyw'> 
>>> inspect.getsourcefile(sys.modules[__name__]) 
'C:\\Python26\\Lib\\idlelib\\idle.pyw' 

: 당신이 IDLE에서 코드의 erroring 부분을 실행하면이 출력을 얻을 네가시키지 않을거야.

당신이 작성한 내용이 길고 짧음은 일을하는 것으로 보이지만 IDLE에서는 실행할 수 없습니다.

+1

inspect.getsourcefile (sys.modules [__name__]) – joaquin

+0

에서 예외가 발생했기 때문에이 문제는 openfile 부분과 관련이 없습니다. 고치고 고쳤습니다. –

3

__file__ 전역 속성을 사용하여 현재 모듈의 소스 경로를 가져올 수 있습니다. 2.6 문서에서

:

__file__ 그것이 파일로부터로드 된 경우 모듈이로드 된 파일의 경로이다. __file__ 속성은 인터럽트에 정적으로 연결된 의 C 모듈에는 없습니다. 확장 모듈이 공유 라이브러리에서 동적으로로드되면 공유 라이브러리 파일의 경로 이름입니다.

는 편집 :

은 내가 __main__ 모듈을 검사 할 때 항상 형식 오류를 슬로우() inspect.getsourcefile 가정을했다. 인터랙티브 인터프리터에서 실행할 때만 그렇습니다. 나는 교정했다. Derp.

관련 문제