3

私は大学のプロジェクトに自己修正コードを使用しています。

ここにあります:

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

私はどんな解決策にも感謝するでしょう。

4

2 に答える 2

4

IDLEの外部で実行すると完全に実行されるため、問題はコードだけではなく、実行している環境にあります。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で実行すると

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

あなたは実際に変更しようとして'C:\\Python26\\Lib\\idlelib\\idle.pyw'います...IDLEはあなたにそれをさせません。

それの長短は、あなたが書いたものが機能するようです:しかし、それはIDLEで実行することはできません。

于 2010-06-02T17:17:05.320 に答える
3

グローバル属性を使用して__file__、現在のモジュールのソース パスを取得できます。

2.6 ドキュメントから:

__file__モジュールがファイルからロードされた場合、モジュールがロードされたファイルのパス名です。この __file__属性は、インタプリタに静的にリンクされている C モジュールには存在しません。共有ライブラリから動的にロードされる拡張モジュールの場合、これは共有ライブラリ ファイルのパス名です。

編集:

__main__モジュールを検査するときに、inspect.getsourcefile() が常に TypeError をスローすると仮定しました。これは、対話型インタープリターから実行する場合のみです。私は訂正します。ダープ。

于 2010-06-02T17:22:39.677 に答える