[파이썬] `sys.flags`: 명령행 플래그 확인

Python provides a sys module that gives you access to various system-specific parameters and functions. One of the useful attributes in this module is sys.flags, which allows you to examine the command-line flags that were used to start the Python interpreter.

What are command-line flags?

Command-line flags are options or settings that can be passed to a program when it is executed from the command line. These flags modify the behavior of the program in some way.

In Python, command-line flags can be used to enable or disable certain features, set specific configurations, or control the runtime behavior of the interpreter.

Accessing sys.flags

To access the command-line flags in Python, you can use the sys.flags attribute. This attribute returns an object that contains several attributes representing different flags that were set when the Python interpreter was started.

Here’s an example of how to use sys.flags:

import sys

# Print the command-line flags
print(sys.flags)

When you run this code, it will display the flags and their corresponding values. The output will look something like this:

sys.flags(debug=0, inspect=0, interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0, hash_randomization=1, isolated=0, dev_mode=None, py3k_warning=0, division_warning=0, malloc_stats=0, no_fsencode_errors=0, no_warnings=0, ignore_unicode_errors=0)

Each flag is represented by an attribute name, followed by its value. The value can be 1 (enabled) or 0 (disabled). Some flags may have additional values or options associated with them.

Example usage

Let’s say you want to check if the -O (optimize) flag was passed when running your Python script. You can do it using sys.flags.optimize:

import sys

if sys.flags.optimize:
    print("Optimization flag (-O) was enabled.")
else:
    print("Optimization flag (-O) was not enabled.")

This code will check if the optimize flag is set to 1, indicating that optimization is enabled. If so, it will print a message confirming that the flag is enabled. Otherwise, it will display a message indicating that the flag is not enabled.

Conclusion

sys.flags provides a convenient way to access and examine the command-line flags that were used when the Python interpreter was started. It allows you to determine the runtime configurations and settings of your script based on the command-line options. This can be useful for implementing different behaviors or optimizations depending on the flags provided.

Explore the various flags available in sys.flags and leverage them to enhance the functionality and performance of your Python programs.