3

Is there a way to execute a method automatically from a python file after each command input while in python interactive?

For example: If I have a method that prints information about file, but I do not want to call that method constantly, how can I make it output after each command in python interactive?

1
  • Python's interactive interpreter is meant to be for simple testing. Check pdb module. As far as I know there's nothing like what you asked. You can very easily wrap your code with testing logic in a module and then test your code interactively, so you don't have to call the function each time. Commented Jun 17, 2017 at 17:52

1 Answer 1

2

sys.displayhook is the function called to display values in the interactive interpreter. You can provide your own that performs other actions:

>>> 2+2
4
>>> original_display_hook = sys.displayhook
>>> def my_display_hook(value):
...     original_display_hook(value)
...     print("Hello there from the hook!")
...
>>> sys.displayhook = my_display_hook
>>> 2+2
4
Hello there from the hook!
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thanks!