@@ -5,7 +5,9 @@ package os
5
5
// license that can be found in the LICENSE file.
6
6
7
7
import (
8
+ "fmt"
8
9
"os"
10
+ "os/exec"
9
11
"reflect"
10
12
"strings"
11
13
@@ -22,6 +24,7 @@ func init() {
22
24
py .MustNewMethod ("putenv" , putenv , 0 , "Set the environment variable named key to the string value." ),
23
25
py .MustNewMethod ("unsetenv" , unsetenv , 0 , "Unset (delete) the environment variable named key." ),
24
26
py .MustNewMethod ("_exit" , _exit , 0 , "Immediate program termination." ),
27
+ py .MustNewMethod ("system" , system , 0 , "Run shell commands, prints stdout directly to deault" ),
25
28
}
26
29
27
30
globals := py.StringDict {
@@ -192,3 +195,30 @@ func _exit(self py.Object, args py.Tuple) (py.Object, error) { // can never retu
192
195
return nil , nil
193
196
}
194
197
}
198
+
199
+ // os.system(command string) this function runs a shell command and directs the output to standard output.
200
+ func system (self py.Object , args py.Tuple ) (py.Object , error ) {
201
+ if len (args ) == 0 {
202
+ return nil , py .ExceptionNewf (py .TypeError , "Expected 1 or more arguments all of type string" )
203
+ } else {
204
+ var cargs []string
205
+ if reflect .TypeOf (args [0 ]).String () == "py.String" {
206
+ _carg , err := py .ReprAsString (args [0 ])
207
+ if err != nil {
208
+ return nil , py .ExceptionNewf (py .TypeError , "Unable to parse string" ) // this will never execute
209
+ }
210
+ carg := strings .ReplaceAll (_carg , "'" , "" ) // required
211
+
212
+ cargs = strings .Split (carg , " " )
213
+ } else {
214
+ return nil , py .ExceptionNewf (py .TypeError , "Expected 1 or more arguments all of type string" )
215
+ }
216
+ command := exec .Command (cargs [0 ])
217
+ outb , err := command .Output ()
218
+ if err != nil {
219
+ return nil , py .ExceptionNewf (py .OSError , err .Error ())
220
+ }
221
+ fmt .Println (string (outb ))
222
+ return py .Int (0 ), nil
223
+ }
224
+ }
0 commit comments