3

I am trying to run following simple code

import sys

print("Starting Test Python Module");

def testmethod():
    print("From test method")

sys.exitfunc = testmethod
print("Terminating Test Python Module");

and it prints

C:\Users\athakur\Softwares>python test.py
Starting Test Python Module
Terminating Test Python Module

I am not able to understand why it does not print "From Test method"

Using atexit works fine though

import atexit

print("Starting Test Python Module");

def testmethod():
    print("From test method")

atexit.register(testmethod)
print("Terminating Test Python Module");

Outputs

C:\Users\athakur\Softwares>python test.py
Starting Test Python Module
Terminating Test Python Module
From test method
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289

2 Answers2

6

sys.exitfunc is deprecated since python2.4 and was removed in python3.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
3

sys.exitfunc does not exist in Python 3.x.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Yes I am using `Python 3.4.3`. So this would explain the behavior. But shouldn't python interpreter complaint about it? – Aniket Thakur Oct 02 '15 at 06:12
  • The protection against arbitrary attributes being added to objects of *types* defined in C apparently doesn't apply to modules. Should it? Possibly. – Ignacio Vazquez-Abrams Oct 02 '15 at 06:16
  • @AniketThakur No, you are simply setting an attribute `exitfunc` to `sys` module, there is nothing wrong about that. You can do `sys.blahblahblah = ` , and it would work ( as long as something is defined :-) , like it works for most other objects in python) . – Anand S Kumar Oct 02 '15 at 06:16