0
# Command Line Interface
1
2
Command-line tool for upgrading Python files with extensive configuration options for different Python versions and preservation settings.
3
4
## Capabilities
5
6
### Main Entry Point
7
8
Main command-line interface function that processes files and applies transformations.
9
10
```python { .api }
11
def main(argv: Sequence[str] | None = None) -> int:
12
"""
13
Main entry point for command-line interface.
14
15
Args:
16
argv: Command line arguments (None uses sys.argv)
17
18
Returns:
19
Exit code:
20
- 0: Success (no changes or --exit-zero-even-if-changed used)
21
- 1: Files were modified or errors occurred
22
"""
23
```
24
25
## Command Line Options
26
27
### Python Version Targets
28
29
```bash
30
# Default (Python 3+)
31
pyupgrade file.py
32
33
# Base version targets
34
pyupgrade --py3-plus file.py # Python 3+ upgrades (alias: --py3-only)
35
pyupgrade --py3-only file.py # Same as --py3-plus
36
37
# Specific version targets
38
pyupgrade --py36-plus file.py
39
pyupgrade --py37-plus file.py
40
pyupgrade --py38-plus file.py
41
pyupgrade --py39-plus file.py
42
pyupgrade --py310-plus file.py
43
pyupgrade --py311-plus file.py
44
pyupgrade --py312-plus file.py
45
pyupgrade --py313-plus file.py
46
pyupgrade --py314-plus file.py
47
```
48
49
### Preservation Options
50
51
```bash
52
# Keep percent-style format strings
53
pyupgrade --keep-percent-format file.py
54
55
# Keep mock imports (don't replace with unittest.mock)
56
pyupgrade --keep-mock file.py
57
58
# Keep runtime typing imports
59
pyupgrade --keep-runtime-typing file.py
60
61
# Exit with code 0 even if files were changed
62
pyupgrade --exit-zero-even-if-changed file.py
63
```
64
65
### Usage Examples
66
67
```bash
68
# Basic usage - upgrade single file
69
pyupgrade example.py
70
71
# Upgrade multiple files
72
pyupgrade src/*.py tests/*.py
73
74
# Upgrade for Python 3.10+ with format preservation
75
pyupgrade --py310-plus --keep-percent-format src/*.py
76
77
# Use with pre-commit (exit 0 on changes)
78
pyupgrade --exit-zero-even-if-changed --py39-plus *.py
79
80
# Process stdin
81
cat example.py | pyupgrade -
82
```
83
84
## Integration Examples
85
86
### Pre-commit Hook
87
88
`.pre-commit-config.yaml`:
89
```yaml
90
repos:
91
- repo: https://github.com/asottile/pyupgrade
92
rev: v3.20.0
93
hooks:
94
- id: pyupgrade
95
args: [--py310-plus]
96
```
97
98
### Custom Script Integration
99
100
```python
101
import subprocess
102
import sys
103
104
def upgrade_codebase():
105
"""Upgrade entire codebase to Python 3.11+."""
106
result = subprocess.run([
107
'pyupgrade',
108
'--py311-plus',
109
'--keep-percent-format',
110
*sys.argv[1:] # Pass through file arguments
111
])
112
return result.returncode
113
114
if __name__ == '__main__':
115
sys.exit(upgrade_codebase())
116
```