or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-interface.mdcolor-system.mdconfiguration.mdcore-formatting.mddefault-hooks.mdglobal-hooks.mdindex.mdprinting.mdutilities.md

cli-interface.mddocs/

0

# Command Line Interface

1

2

Command-line tool for running Python scripts with enhanced traceback display. Provides a wrapper that executes Python scripts with automatic variable display in tracebacks, supporting all formatting options available in the library.

3

4

## Capabilities

5

6

### Script Execution with Enhanced Tracebacks

7

8

Run Python scripts with enhanced traceback output and configurable formatting options.

9

10

```python { .api }

11

def run_script(

12

path: Path,

13

argv: List[str],

14

fmt: Format,

15

) -> int:

16

"""

17

Execute a Python script with enhanced traceback handling.

18

19

Sets up the execution environment with proper sys.path and sys.argv,

20

then executes the script with enhanced exception handling using

21

the printing_exc context manager.

22

23

Parameters:

24

- path: Path to the Python script to execute

25

- argv: Command-line arguments to pass to the script

26

- fmt: Format configuration for traceback display

27

28

Returns:

29

0 if script executed successfully, 1 if exception occurred

30

"""

31

32

def main() -> int:

33

"""

34

Main entry point for the command-line interface.

35

36

Parses command-line arguments, configures formatting options,

37

and executes the specified script with enhanced tracebacks.

38

39

Returns:

40

Exit code (0 for success, 1 for error)

41

"""

42

```

43

44

### Argument Parsing

45

46

Parse command-line arguments for script execution and formatting configuration.

47

48

```python { .api }

49

def parse_args() -> Tuple[argparse.Namespace, Path, List[str]]:

50

"""

51

Parse command-line arguments for the CLI interface.

52

53

Supports all Format configuration options as command-line arguments

54

plus script path and script arguments.

55

56

Returns:

57

Tuple of (parsed_arguments, script_path, script_arguments)

58

"""

59

60

def parse_args_and_script_cmd(

61

raising_nohelp_noabbrev_parser: argparse.ArgumentParser,

62

) -> Tuple[argparse.Namespace, Path, List[str]]:

63

"""

64

Parse arguments and separate tool args from script command.

65

66

Parameters:

67

- raising_nohelp_noabbrev_parser: ArgumentParser with custom error handling

68

69

Returns:

70

Tuple of (parsed_arguments, script_path, script_arguments)

71

"""

72

73

def split_argv_to_own_and_script(

74

raising_noabbrev_parser: argparse.ArgumentParser,

75

argv: Optional[List[str]] = None,

76

) -> Tuple[List[str], List[str]]:

77

"""

78

Split command line arguments into tool args and script args.

79

80

Parameters:

81

- raising_noabbrev_parser: ArgumentParser instance

82

- argv: Arguments to parse (uses sys.argv if None)

83

84

Returns:

85

Tuple of (tool_arguments, script_arguments)

86

"""

87

```

88

89

### Error Handling

90

91

Custom exception handling for argument parsing.

92

93

```python { .api }

94

class ParseError(RuntimeError):

95

"""Exception raised for argument parsing errors."""

96

pass

97

98

def raising_error_func(message: str) -> None:

99

"""

100

Error function that raises ParseError instead of calling sys.exit.

101

102

Parameters:

103

- message: Error message to include in exception

104

105

Raises:

106

ParseError with the provided message

107

"""

108

```

109

110

## Usage Examples

111

112

### Basic Command Line Usage

113

114

```bash

115

# Run a Python script with enhanced tracebacks

116

traceback-with-variables my_script.py

117

118

# Run with command line arguments

119

traceback-with-variables my_script.py --input data.txt --output results.txt

120

121

# Run a module

122

traceback-with-variables -m my_module arg1 arg2

123

```

124

125

### Formatting Options via Command Line

126

127

```bash

128

# Custom value string length

129

traceback-with-variables --max-value-str-len 500 my_script.py

130

131

# Show context lines around errors

132

traceback-with-variables --before 2 --after 1 my_script.py

133

134

# Use specific color scheme

135

traceback-with-variables --color-scheme synthwave my_script.py

136

137

# Hide global variables

138

traceback-with-variables --no-globals my_script.py

139

140

# Multiple formatting options

141

traceback-with-variables \

142

--max-value-str-len 300 \

143

--color-scheme nice \

144

--before 1 \

145

--after 1 \

146

--objects-details 2 \

147

my_script.py input.dat

148

```

149

150

### File Pattern Filtering

151

152

```bash

153

# Only show frames from specific files

154

traceback-with-variables --skip-files-except ".*myproject.*" ".*main\.py" my_script.py

155

156

# Show brief output for certain files

157

traceback-with-variables --brief-files-except ".*third_party.*" my_script.py

158

```

159

160

### Programmatic CLI Usage

161

162

```python

163

from traceback_with_variables.main import run_script, parse_args, Format

164

from pathlib import Path

165

166

# Parse command line arguments

167

args, script_path, script_argv = parse_args()

168

169

# Create format from parsed arguments

170

fmt = Format.parse(args)

171

172

# Run the script

173

exit_code = run_script(

174

path=script_path,

175

argv=script_argv,

176

fmt=fmt

177

)

178

179

print(f"Script completed with exit code: {exit_code}")

180

```

181

182

### Custom Script Runner

183

184

```python

185

from traceback_with_variables.main import run_script

186

from traceback_with_variables import Format, ColorSchemes

187

from pathlib import Path

188

189

# Custom format for script execution

190

custom_fmt = Format(

191

max_value_str_len=400,

192

color_scheme=ColorSchemes.synthwave,

193

before=1,

194

after=1,

195

objects_details=2

196

)

197

198

# Run script with custom format

199

script_path = Path("debug_script.py")

200

script_args = ["--debug", "--input", "test_data.json"]

201

202

exit_code = run_script(

203

path=script_path,

204

argv=script_args,

205

fmt=custom_fmt

206

)

207

208

if exit_code == 0:

209

print("Script completed successfully")

210

else:

211

print("Script encountered an exception")

212

```

213

214

### Integration with Development Tools

215

216

```python

217

import subprocess

218

import sys

219

from pathlib import Path

220

221

def run_with_enhanced_tracebacks(script_path: str, *args):

222

"""Run a Python script with enhanced tracebacks via CLI."""

223

cmd = [

224

sys.executable,

225

"-m", "traceback_with_variables",

226

"--color-scheme", "nice",

227

"--before", "1",

228

"--after", "1",

229

script_path

230

] + list(args)

231

232

result = subprocess.run(cmd, capture_output=True, text=True)

233

234

print("STDOUT:")

235

print(result.stdout)

236

print("\nSTDERR (with enhanced tracebacks):")

237

print(result.stderr)

238

239

return result.returncode

240

241

# Usage

242

exit_code = run_with_enhanced_tracebacks("test_script.py", "--verbose")

243

```

244

245

### Argument Parsing Examples

246

247

```python

248

import argparse

249

from traceback_with_variables import Format

250

251

# Create parser with Format arguments

252

parser = argparse.ArgumentParser(description="My application")

253

Format.add_arguments(parser)

254

255

# Add application-specific arguments

256

parser.add_argument("--input", help="Input file")

257

parser.add_argument("--output", help="Output file")

258

259

# Parse arguments

260

args = parser.parse_args()

261

262

# Create format from parsed args

263

fmt = Format.parse(args)

264

265

# Use format in application

266

print(f"Using format with max_value_str_len: {fmt.max_value_str_len}")

267

print(f"Color scheme: {fmt.color_scheme}")

268

```

269

270

### Script Execution Environment

271

272

```python

273

from traceback_with_variables.main import run_script

274

from traceback_with_variables import Format

275

from pathlib import Path

276

277

# The run_script function sets up the execution environment:

278

# - sys.path[0] = str(path.parent) # Script directory in path

279

# - sys.argv = [str(path)] + argv # Script args

280

# - Proper __name__ = '__main__' # Main module execution

281

# - Enhanced exception handling # Via printing_exc context

282

283

# Example of what happens internally:

284

script_path = Path("example.py")

285

script_args = ["arg1", "arg2"]

286

fmt = Format()

287

288

# This is equivalent to:

289

# cd /path/to/script/directory

290

# python example.py arg1 arg2

291

# but with enhanced tracebacks

292

293

exit_code = run_script(script_path, script_args, fmt)

294

```

295

296

### Help and Usage Information

297

298

```bash

299

# Show help for all available options

300

traceback-with-variables --help

301

302

# Available options include:

303

# --max-value-str-len INT Maximum length for variable values (default: 1000)

304

# --ellipsis-rel-pos FLOAT Ellipsis position (default: 0.7)

305

# --max-exc-str-len INT Maximum exception string length (default: 10000)

306

# --objects-details INT Object inspection depth (default: 1)

307

# --ellipsis STRING Ellipsis string (default: ...)

308

# --before INT Context lines before error (default: 0)

309

# --after INT Context lines after error (default: 0)

310

# --color-scheme SCHEME Color scheme: auto, none, common, synthwave, nice

311

# --skip-files-except PATTERN File patterns to skip unless matching

312

# --brief-files-except PATTERN File patterns for brief output

313

# --no-globals Hide global variables

314

```

315

316

### Advanced CLI Integration

317

318

```python

319

import os

320

import sys

321

from traceback_with_variables.main import main

322

323

# Programmatically invoke the CLI

324

original_argv = sys.argv.copy()

325

326

try:

327

# Set up arguments for CLI

328

sys.argv = [

329

"traceback-with-variables",

330

"--color-scheme", "synthwave",

331

"--max-value-str-len", "300",

332

"--before", "1",

333

"target_script.py",

334

"--script-arg", "value"

335

]

336

337

# Run the CLI

338

exit_code = main()

339

print(f"CLI completed with exit code: {exit_code}")

340

341

finally:

342

# Restore original argv

343

sys.argv = original_argv

344

```