簡體   English   中英

從其他腳本調用時可以工作的python atexit模塊的替代方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM