# Python Sys Module

The `sys` module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

## Importing the Module

```python
import sys
```

## Command Line Arguments

The list of command line arguments passed to a Python script. `sys.argv[0]` is the script name.

```python
import sys

print(f"Script name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
```

## Exiting the Program

`sys.exit()` allows you to exit from Python. You can pass an optional integer exit code (0 is success, non-zero is error) or a string (printed to stderr and code 1 returned).

```python
import sys

# Exit with success
# sys.exit(0)

# Exit with error message
# sys.exit("An error occurred")
```

## Standard I/O

File objects corresponding to the interpreter’s standard input, output, and error streams.

```python
import sys

# Write to stdout
sys.stdout.write("Hello stdout\n")

# Write to stderr
sys.stderr.write("Hello stderr\n")

# Read from stdin
# input_data = sys.stdin.readline()
```

## Python Path

`sys.path` is a list of strings that specifies the search path for modules. Initialized from the environment variable `PYTHONPATH`, plus an installation-dependent default.

```python
import sys

print(sys.path)

# Add a directory to the path
sys.path.append('/path/to/my/modules')
```

## System Information

### Platform

```python
print(sys.platform) # e.g., 'linux', 'win32', 'darwin'
```

### Python Version

```python
print(sys.version)
print(sys.version_info)
```

## Modules

`sys.modules` is a dictionary that maps module names to modules which have already been loaded.

```python
import sys

print(sys.modules.keys())
```

## Reference Counting

`sys.getrefcount()` returns the reference count of an object.

```python
import sys

a = []
print(sys.getrefcount(a))
```

[[programming/python/python]]