![](/img/trans.png)
[英]Sequence of object cleanup and functions called by atexit in Python module
[英]Alternative to python atexit module that works when called from other scripts
在您的python腳本退出時,使用atexit.register(function)
注冊要調用的函數是一種常見的做法。
問題是我發現了一個以丑陋的方式失敗的情況:如果您的腳本是使用execfile()
從另一個python腳本執行的。
在這種情況下,您會發現Python退出后將無法定位您的函數,這很有意義。
我的問題是如何以不出現此問題的方式保留此功能。
我認為您遇到的問題是當前工作目錄的位置。 您可以確保執行以下操作來指定正確的位置:
import os
target = os.path.join(os.path.dirname(__file__), "mytarget.py")
這對我有用。 我創建了一個要由另一個文件a.py
執行的文件:
$ cat a.py
import atexit
@atexit.register
def myexit():
print 'myexit in a.py'
然后b.py
調用execfile:
$ cat b.py
import atexit
@atexit.register
def b_myexit():
print 'b_myexit in b.py'
execfile('a.py')
當我運行b.py
,兩個注冊函數都被調用:
$ python b.py
myexit in a.py
b_myexit in b.py
請注意,當我運行它們時,這兩個腳本都位於同一目錄中。 如果您的a.py
位於Ryan Ginstrom在回答中提到的單獨目錄中,則需要使用完整路徑,例如:
execfile('/path/to/a.py')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.