Skip to content

Commit 5d12b75

Browse files
authored
Add docs on the main function, argv and return codes (#470)
Adds a documentation page for current info on the `main` function, and optionally providing command line arguments and return codes. Based on the work in #353 and elsewhere.
2 parents fc35d2b + f1e5bcb commit 5d12b75

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

docs/mkdocs.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ markdown_extensions:
4949
nav:
5050
- Home: index.md
5151
- contributing.md
52+
- Language Features:
53+
- howto/main_function.md
5254
- API Reference:
5355
- api_reference/python_builtins.md
5456
- Unsorted notes:

docs/src/howto/main_function.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
title: The Main Function
2+
---
3+
4+
All SPy programs that are run in the interpreter or compiled must have a `main` function. The main function is the entry point of the program, and it is where the execution of the program begins.
5+
6+
```py
7+
def main() -> None:
8+
print("Hello world")
9+
```
10+
11+
Not every `.spy` module needs a main function, but the module invoked by, e.g. `spy foo.spy` `spy build foo.spy` must contain a main function.
12+
13+
Modules which are compiled as a library (e.g. `spy build --target lib foo.spy` or `--target py-cffi`) do not need a main function.
14+
15+
## Return Codes
16+
17+
The `main` function may be typed to return an `int` (`i32`). If so, the return value of the main function will be the return value of the program:
18+
19+
```py
20+
#retcode.spy
21+
def main() -> int
22+
return 123
23+
```
24+
```
25+
$ uv run spy retcode.spy
26+
$ echo $?
27+
123
28+
```
29+
30+
31+
## Accessing Command Line Arguments
32+
33+
If the `main` function accepts a list of strings as an argument, the SPy program will accept arguments from the command line, both when running in interpreted
34+
35+
```py
36+
#args.spy
37+
def main(args: list[str]) -> None:
38+
print(args[1])
39+
```
40+
```
41+
$ uv run spy args.spy 999
42+
999
43+
```
44+
45+
As with CPython, args[0] is the name of the string passed to the uv runtime. This is the equivalent of CPython's `sys.argv`:
46+
47+
```py
48+
#argname.spy
49+
def main(argv: list[str]) -> None:
50+
print(args[0])
51+
```
52+
```
53+
$ uv run spy argname.spy
54+
foo.spy
55+
```

0 commit comments

Comments
 (0)