【问题标题】:Alternative to python atexit module that works when called from other scripts替代从其他脚本调用时工作的 python atexit 模块
【发布时间】:2010-09-08 09:54:04
【问题描述】:

使用atexit.register(function) 注册一个在你的python 脚本退出时调用的函数是一种常见的做法。

问题是我发现了一个失败的例子:如果你的脚本使用execfile()从另一个python脚本执行。

在这种情况下,您会发现 Python 在退出时将无法定位您的函数,这是有道理的。

我的问题是如何以不存在此问题的方式保留此功能。

【问题讨论】:

  • 你能提供更多细节吗?一个失败的样本?正如@bstpierre 所示,它似乎工作正常。

标签: python atexit execfile


【解决方案1】:

我认为您遇到的问题是当前工作目录的位置。您可以通过以下方式确保指定正确的位置:

import os

target = os.path.join(os.path.dirname(__file__), "mytarget.py")

【讨论】:

    【解决方案2】:

    这对我有用。我创建了一个要由另一个文件执行的文件,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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      相关资源
      最近更新 更多