Skip to content

Commit e7dcdff

Browse files
committed
all: handle SystemExit
1 parent 53b7b8e commit e7dcdff

File tree

3 files changed

+66
-1
lines changed

3 files changed

+66
-1
lines changed

main.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,36 @@ func xmain(args []string) {
7474
} else {
7575
_, err := py.RunFile(ctx, args[0], py.CompileOpts{}, nil)
7676
if err != nil {
77+
if py.IsException(py.SystemExit, err) {
78+
args := err.(py.ExceptionInfo).Value.(*py.Exception).Args.(py.Tuple)
79+
if len(args) == 0 {
80+
os.Exit(0)
81+
} else if len(args) == 1 {
82+
if code, ok := args[0].(py.Int); ok {
83+
c, err := code.GoInt()
84+
if err != nil {
85+
fmt.Fprintln(os.Stderr, err)
86+
os.Exit(1)
87+
}
88+
os.Exit(c)
89+
}
90+
msg, err := py.ReprAsString(args[0])
91+
if err != nil {
92+
fmt.Fprintln(os.Stderr, err)
93+
} else {
94+
fmt.Fprintln(os.Stderr, msg)
95+
}
96+
os.Exit(1)
97+
} else {
98+
msg, err := py.ReprAsString(args)
99+
if err != nil {
100+
fmt.Fprintln(os.Stderr, err)
101+
} else {
102+
fmt.Fprintln(os.Stderr, msg)
103+
}
104+
os.Exit(1)
105+
}
106+
}
77107
py.TracebackDump(err)
78108
os.Exit(1)
79109
}

repl/repl.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package repl
77

88
import (
99
"fmt"
10+
"os"
1011
"sort"
1112
"strings"
1213

@@ -109,6 +110,36 @@ func (r *REPL) Run(line string) {
109110
}
110111
_, err = r.Context.RunCode(code, r.Module.Globals, r.Module.Globals, nil)
111112
if err != nil {
113+
if py.IsException(py.SystemExit, err) {
114+
args := err.(py.ExceptionInfo).Value.(*py.Exception).Args.(py.Tuple)
115+
if len(args) == 0 {
116+
os.Exit(0)
117+
} else if len(args) == 1 {
118+
if code, ok := args[0].(py.Int); ok {
119+
c, err := code.GoInt()
120+
if err != nil {
121+
fmt.Fprintln(os.Stderr, err)
122+
os.Exit(1)
123+
}
124+
os.Exit(c)
125+
}
126+
msg, err := py.ReprAsString(args[0])
127+
if err != nil {
128+
fmt.Fprintln(os.Stderr, err)
129+
} else {
130+
fmt.Fprintln(os.Stderr, msg)
131+
}
132+
os.Exit(1)
133+
} else {
134+
msg, err := py.ReprAsString(args)
135+
if err != nil {
136+
fmt.Fprintln(os.Stderr, err)
137+
} else {
138+
fmt.Fprintln(os.Stderr, msg)
139+
}
140+
os.Exit(1)
141+
}
142+
}
112143
py.TracebackDump(err)
113144
}
114145
}

stdlib/sys/sys.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,11 @@ func sys_exit(self py.Object, args py.Tuple) (py.Object, error) {
133133
return nil, err
134134
}
135135
// Raise SystemExit so callers may catch it or clean up.
136-
return py.ExceptionNew(py.SystemExit, args, nil)
136+
exc, err := py.ExceptionNew(py.SystemExit, args, nil)
137+
if err != nil {
138+
return nil, err
139+
}
140+
return nil, exc.(*py.Exception)
137141
}
138142

139143
const getdefaultencoding_doc = `getdefaultencoding() -> string

0 commit comments

Comments
 (0)