0
# Main Interface Functions
1
2
Core functions for running pylama code analysis programmatically and via command line interface. These functions provide the primary entry points for both interactive command-line usage and programmatic integration.
3
4
## Capabilities
5
6
### Command Line Entry Point
7
8
Main console command entry point that parses arguments, loads configuration, and executes code checking.
9
10
```python { .api }
11
def shell(args: List[str] = None, error: bool = True):
12
"""
13
Main console entry point for pylama command.
14
15
Args:
16
args: Command line arguments list. If None, uses sys.argv[1:]
17
error: Whether to exit with error code on finding issues
18
19
Returns:
20
List[Error]: List of errors found during checking
21
22
This function:
23
- Parses command line arguments and configuration files
24
- Sets up logging based on options
25
- Handles special modes (VCS hook installation, stdin input)
26
- Executes file checking and displays results
27
- Exits with appropriate code if error=True
28
"""
29
```
30
31
### Multi-File Checking
32
33
Check multiple file paths with support for directory traversal and filtering.
34
35
```python { .api }
36
def check_paths(
37
paths: Optional[List[str]],
38
options: Namespace,
39
code: str = None,
40
rootdir: Path = None,
41
) -> List[Error]:
42
"""
43
Check multiple file paths for code quality issues.
44
45
Args:
46
paths: List of file/directory paths to check. If None, uses options.paths
47
options: Parsed configuration options from parse_options()
48
code: Source code string for checking (used with single path)
49
rootdir: Root directory for relative path resolution
50
51
Returns:
52
List[Error]: All errors found across all checked files
53
54
This function:
55
- Expands directories to find Python files
56
- Filters files based on configuration
57
- Supports both synchronous and asynchronous processing
58
- Aggregates errors from all files
59
"""
60
```
61
62
### Single File Checking
63
64
Core function for checking individual files with full linter integration.
65
66
```python { .api }
67
def run(
68
path: str,
69
code: str = None,
70
rootdir: Path = CURDIR,
71
options: Namespace = None
72
) -> List[Error]:
73
"""
74
Run code checkers on a single file.
75
76
Args:
77
path: File path to check (relative to rootdir)
78
code: Source code string. If None, reads from file
79
rootdir: Root directory for path resolution
80
options: Configuration options. If None, uses defaults
81
82
Returns:
83
List[Error]: Errors found in the file
84
85
This function:
86
- Creates RunContext for the file
87
- Processes file-specific configuration and modelines
88
- Runs all configured linters on the file
89
- Collects and deduplicates errors
90
- Applies sorting based on configuration
91
"""
92
```
93
94
### Error Display
95
96
Format and display errors using configured output format.
97
98
```python { .api }
99
def display_errors(errors: List[Error], options: Namespace):
100
"""
101
Format and display errors using specified format.
102
103
Args:
104
errors: List of Error objects to display
105
options: Configuration options containing format settings
106
107
Supported formats:
108
- 'json': JSON array of error dictionaries
109
- 'pylint': Pylint-compatible format
110
- 'pycodestyle': pycodestyle-compatible format
111
- 'parsable': Default parsable format
112
- Custom format strings using error attributes
113
114
Output is sent to logger at WARNING level.
115
"""
116
```
117
118
### Legacy Interface
119
120
Deprecated function maintained for backward compatibility.
121
122
```python { .api }
123
def check_path(
124
options: Namespace,
125
rootdir: str = None,
126
candidates: List[str] = None,
127
code: str = None,
128
) -> List[Error]:
129
"""
130
Legacy interface for checking files (deprecated).
131
132
This function is deprecated and will be removed in pylama 9.
133
Use check_paths() instead.
134
135
Args:
136
options: Configuration options
137
rootdir: Root directory path as string
138
candidates: List of file paths to check
139
code: Source code string
140
141
Returns:
142
List[Error]: Errors found during checking
143
"""
144
```
145
146
## Usage Examples
147
148
### Basic Programmatic Usage
149
150
```python
151
from pylama.main import check_paths
152
from pylama.config import parse_options
153
154
# Check files with default configuration
155
options = parse_options([])
156
errors = check_paths(['mymodule.py', 'tests/'], options)
157
158
# Process results
159
if errors:
160
print(f"Found {len(errors)} issues:")
161
for error in errors:
162
print(f" {error.filename}:{error.lnum} - {error.message}")
163
```
164
165
### Custom Configuration
166
167
```python
168
from pylama.main import check_paths
169
from pylama.config import parse_options
170
171
# Use specific linters and options
172
args = [
173
'--linters=pycodestyle,pyflakes,mccabe',
174
'--ignore=E501,W503',
175
'--max-line-length=100',
176
'src/'
177
]
178
options = parse_options(args)
179
errors = check_paths(None, options) # Uses paths from options
180
```
181
182
### Single File with Code String
183
184
```python
185
from pylama.core import run
186
from pylama.config import parse_options
187
188
# Check code string directly
189
code = '''
190
def my_function():
191
unused_var = 42
192
print("Hello World")
193
'''
194
195
options = parse_options(['--linters=pyflakes'])
196
errors = run('example.py', code=code, options=options)
197
198
for error in errors:
199
print(f"Line {error.lnum}: {error.message}")
200
```
201
202
### Command Line Integration
203
204
```python
205
import sys
206
from pylama.main import shell
207
208
# Run as if from command line
209
sys.argv = ['pylama', '--format=json', 'myproject/']
210
errors = shell(error=False) # Don't exit on errors
211
212
# Or with explicit arguments
213
errors = shell(['--linters=pylint', '--ignore=C0111', 'myfile.py'])
214
```
215
216
## Constants
217
218
```python { .api }
219
DEFAULT_FORMAT: str = "{filename}:{lnum}:{col} [{etype}] {number} {message} [{source}]"
220
221
MESSAGE_FORMATS: Dict[str, str] = {
222
"pylint": "{filename}:{lnum}: [{etype}] {number} {message} [{source}]",
223
"pycodestyle": "{filename}:{lnum}:{col} {number} {message} [{source}]",
224
"parsable": DEFAULT_FORMAT,
225
}
226
```