[파이썬] `sys.displayhook()`: 인터프리터 출력 제어

The Python sys.displayhook() function plays an important role in controlling the output displayed by the Python interpreter. It specifies how the resulting value of an expression is displayed in the interactive shell. Understanding how to customize sys.displayhook() can help improve the readability and usability of your code.

By default, sys.displayhook() is set to sys.__displayhook__, which uses the repr() function to display the output. This means that the output will be represented as a string that can be evaluated to recreate the original object. While this is useful, sometimes we might want to have more control over how the output is displayed.

Let’s look at an example to understand how sys.displayhook() works and how we can modify it:

import sys

# Custom displayhook function
def custom_displayhook(value):
    if isinstance(value, str):
        # Display strings in uppercase
        formatted_value = value.upper()
    else:
        # Use the default displayhook for other types
        formatted_value = sys.__displayhook__(value)

    sys.stdout.write(formatted_value + '\n')

# Replace sys.displayhook with the custom function
sys.displayhook = custom_displayhook

# Now let's try it out
message = "Hello, World!"
print(message)

In this example, we define a custom displayhook function called custom_displayhook(). It checks if the value is a string and if so, formats it to display in uppercase. For other types, we use the default displayhook function.

We then replace the sys.displayhook with our custom function by assigning sys.displayhook = custom_displayhook.

When we run the code and print the message, instead of seeing "Hello, World!", it will be displayed as "HELLO, WORLD!".

By customizing sys.displayhook(), you have the power to control how the output is displayed in the Python interpreter. This can be especially useful when working with specific data types or when you want to add additional formatting to the output.

Remember, sys.displayhook() is just one of the many powerful features that Python provides for customization and control. Explore the Python documentation to discover more exciting possibilities to enhance your programming experience!