80. Python's sys Module

Here are 10 Python code snippets that demonstrate different use cases of Python's sys module:

1. Accessing Command-Line Arguments

This example shows how to retrieve command-line arguments using sys.argv.

Copy

import sys

if __name__ == "__main__":
    print("Command-line arguments:")
    for arg in sys.argv:
        print(arg)

2. Exiting a Program with sys.exit()

You can use sys.exit() to exit a program gracefully, optionally providing an exit status.

Copy

import sys

def main():
    print("This is an example of sys.exit()")
    sys.exit(0)

if __name__ == "__main__":
    main()

3. Redirecting Output Using sys.stdout

This example demonstrates redirecting standard output to a file.

Copy


4. Checking the Python Version with sys.version

You can check the version of Python being used with sys.version.

Copy


5. Working with sys.path for Importing Modules

This example shows how to manipulate sys.path to control module search paths.

Copy


6. Getting the Size of an Object with sys.getsizeof()

This example shows how to use sys.getsizeof() to get the size of an object in bytes.

Copy


7. Handling Standard Error Output with sys.stderr

This example shows how to write error messages to sys.stderr.

Copy


8. Getting the Recursion Limit with sys.getrecursionlimit()

You can check and set the recursion limit using sys.getrecursionlimit() and sys.setrecursionlimit().

Copy


9. Using sys.stdin for User Input

This example uses sys.stdin to read user input.

Copy


10. Exiting with an Error Code Using sys.exit()

This snippet shows how to exit a program with a specific error code.

Copy


Last updated