Read command-line arguments
A script needs positional inputs supplied by the shell.
Python · Module
Python’s always-available sys module exposes interpreter-maintained values and runtime-oriented functions. It is commonly used for command-line arguments, executable and version details, loaded modules, import paths, and object-size inspection.
The always-available sys module exposes interpreter-maintained values and functions that interact closely with the Python runtime. Common read-only attributes describe the executable, loaded modules, command-line arguments, platform details, and version; functions provide runtime operations such as measuring an object's size.
import sys
sys.argv
sys.executable
sys.modules
sys.getsizeof(object)| Name | Type | Description |
|---|---|---|
object | object | For sys.getsizeof(object), the object whose size is requested; it can be any type of object. |
sys.getsizeof(object) returns the size of the object in bytes; other sys attributes documented here expose interpreter state rather than returning values from a common call.
import sys
print(f"Python {sys.version_info.major}.{sys.version_info.minor}")
print(f"Executable: {sys.executable}")
print(f"Arguments: {sys.argv[1:]}")Displays interpreter version components, executable path, and command-line arguments.
A script needs positional inputs supplied by the shell.
A tool must report which Python binary is running it.
Diagnostics need to inspect import state or estimate an object's shallow size.
sys is always available and provides access to values maintained by the interpreter plus functions that interact strongly with it. Examples include sys.argv, sys.executable, sys.modules, and sys.getsizeof().
Follow-up: How would you discover which modules are already loaded? Read sys.modules, a dictionary mapping module names to their loaded module objects.
sys.argv contains command-line arguments, with the script name conventionally at index 0. The remaining entries represent arguments supplied after the script name.
Follow-up: How would you make a command-line argument optional? Check the length of sys.argv before indexing and provide a default when the requested position is absent.
sys.getsizeof(object) returns the object's size in bytes. The argument can be any object, but the result concerns that object rather than recursively measuring objects it references.
Follow-up: Why should this not be treated as a complete memory profiler? Referenced objects may have their own storage, so measuring one object does not account for an entire object graph.
sys.argvsys.executablesys.modulessys.version_infosys.getsizeofsys.path