forked from go-python/gpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathos.go
228 lines (206 loc) · 6.93 KB
/
os.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright 2022 The go-python Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package os implements the Python os module.
package os
import (
"os"
"os/exec"
"runtime"
"strings"
"github.com/go-python/gpython/py"
)
var (
osSep = py.String("/")
osName = py.String("posix")
osPathsep = py.String(":")
osLinesep = py.String("\n")
osDefpath = py.String(":/bin:/usr/bin")
osDevnull = py.String("/dev/null")
osAltsep py.Object = py.None
)
func initGlobals() {
switch runtime.GOOS {
case "android":
osName = py.String("java")
case "windows":
osSep = py.String(`\`)
osName = py.String("nt")
osPathsep = py.String(";")
osLinesep = py.String("\r\n")
osDefpath = py.String(`C:\bin`)
osDevnull = py.String("nul")
osAltsep = py.String("/")
}
}
func init() {
initGlobals()
methods := []*py.Method{
py.MustNewMethod("getcwd", getCwd, 0, "Get the current working directory"),
py.MustNewMethod("getcwdb", getCwdb, 0, "Get the current working directory in a byte slice"),
py.MustNewMethod("chdir", chdir, 0, "Change the current working directory"),
py.MustNewMethod("getenv", getenv, 0, "Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are str."),
py.MustNewMethod("getpid", getpid, 0, "Return the current process id."),
py.MustNewMethod("putenv", putenv, 0, "Set the environment variable named key to the string value."),
py.MustNewMethod("unsetenv", unsetenv, 0, "Unset (delete) the environment variable named key."),
py.MustNewMethod("_exit", _exit, 0, "Immediate program termination."),
py.MustNewMethod("system", system, 0, "Run shell commands, prints stdout directly to deault"),
}
globals := py.StringDict{
"error": py.OSError,
"environ": getEnvVariables(),
"sep": osSep,
"name": osName,
"curdir": py.String("."),
"pardir": py.String(".."),
"extsep": py.String("."),
"altsep": osAltsep,
"pathsep": osPathsep,
"linesep": osLinesep,
"defpath": osDefpath,
"devnull": osDevnull,
}
py.RegisterModule(&py.ModuleImpl{
Info: py.ModuleInfo{
Name: "os",
Doc: "Miscellaneous operating system interfaces",
},
Methods: methods,
Globals: globals,
})
}
// getEnvVariables returns the dictionary of environment variables.
func getEnvVariables() py.StringDict {
vs := os.Environ()
dict := py.NewStringDictSized(len(vs))
for _, evar := range vs {
key_value := strings.SplitN(evar, "=", 2) // returns a []string containing [key,value]
dict.M__setitem__(py.String(key_value[0]), py.String(key_value[1]))
}
return dict
}
// getCwd returns the current working directory.
func getCwd(self py.Object, args py.Tuple) (py.Object, error) {
dir, err := os.Getwd()
if err != nil {
return nil, py.ExceptionNewf(py.OSError, "Unable to get current working directory.")
}
return py.String(dir), nil
}
// getCwdb returns the current working directory as a byte list.
func getCwdb(self py.Object, args py.Tuple) (py.Object, error) {
dir, err := os.Getwd()
if err != nil {
return nil, py.ExceptionNewf(py.OSError, "Unable to get current working directory.")
}
return py.Bytes(dir), nil
}
// chdir changes the current working directory to the provided path.
func chdir(self py.Object, args py.Tuple) (py.Object, error) {
if len(args) == 0 {
return nil, py.ExceptionNewf(py.TypeError, "Missing required argument 'path' (pos 1)")
}
dir, ok := args[0].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "str expected, not "+args[0].Type().Name)
}
err := os.Chdir(string(dir))
if err != nil {
return nil, py.ExceptionNewf(py.NotADirectoryError, "Couldn't change cwd; "+err.Error())
}
return py.None, nil
}
// getenv returns the value of the environment variable key.
// If no such environment variable exists and a default value was provided, that value is returned.
func getenv(self py.Object, args py.Tuple) (py.Object, error) {
if len(args) < 1 {
return nil, py.ExceptionNewf(py.TypeError, "missing one required argument: 'name:str'")
}
k, ok := args[0].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "str expected (pos 1), not "+args[0].Type().Name)
}
v, ok := os.LookupEnv(string(k))
if ok {
return py.String(v), nil
}
if len(args) == 2 {
return args[1], nil
}
return py.None, nil
}
// getpid returns the current process id.
func getpid(self py.Object, args py.Tuple) (py.Object, error) {
return py.Int(os.Getpid()), nil
}
// putenv sets the value of an environment variable named by the key.
func putenv(self py.Object, args py.Tuple) (py.Object, error) {
if len(args) != 2 {
return nil, py.ExceptionNewf(py.TypeError, "missing required arguments: 'key:str' and 'value:str'")
}
k, ok := args[0].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "str expected (pos 1), not "+args[0].Type().Name)
}
v, ok := args[1].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "str expected (pos 2), not "+args[1].Type().Name)
}
err := os.Setenv(string(k), string(v))
if err != nil {
return nil, py.ExceptionNewf(py.OSError, "Unable to set enviroment variable")
}
return py.None, nil
}
// Unset (delete) the environment variable named key.
func unsetenv(self py.Object, args py.Tuple) (py.Object, error) {
if len(args) != 1 {
return nil, py.ExceptionNewf(py.TypeError, "missing one required argument: 'key:str'")
}
k, ok := args[0].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "str expected (pos 1), not "+args[0].Type().Name)
}
err := os.Unsetenv(string(k))
if err != nil {
return nil, py.ExceptionNewf(py.OSError, "Unable to unset enviroment variable")
}
return py.None, nil
}
// os._exit() immediate program termination; unlike sys.exit(), which raises a SystemExit, this function will termninate the program immediately.
func _exit(self py.Object, args py.Tuple) (py.Object, error) { // can never return
if len(args) == 0 {
os.Exit(0)
}
arg, ok := args[0].(py.Int)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "expected int (pos 1), not "+args[0].Type().Name)
}
os.Exit(int(arg))
return nil, nil
}
// os.system(command string) this function runs a shell command and directs the output to standard output.
func system(self py.Object, args py.Tuple) (py.Object, error) {
if len(args) != 1 {
return nil, py.ExceptionNewf(py.TypeError, "missing one required argument: 'command:str'")
}
arg, ok := args[0].(py.String)
if !ok {
return nil, py.ExceptionNewf(py.TypeError, "str expected (pos 1), not "+args[0].Type().Name)
}
var command *exec.Cmd
if runtime.GOOS != "windows" {
command = exec.Command("/bin/sh", "-c", string(arg))
} else {
command = exec.Command("cmd.exe", string(arg))
}
outb, err := command.CombinedOutput() // - commbinedoutput to get both stderr and stdout -
if err != nil {
return nil, py.ExceptionNewf(py.OSError, err.Error())
}
ok = py.Println(self, string(outb))
if !ok {
return py.Int(1), nil
}
return py.Int(0), nil
}