Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Run External Python script

Tags:

go

exec

I have tried following the Go Docs in order to call a python script which just outputs "Hello" from GO, but have failed until now.

exec.Command("script.py")

or I've also tried calling a shell script which simply calls the python script, but also failed:

exec.Command("job.sh")

Any ideas how would I achieve this?

EDIT

I solved following the suggestion in the comments and adding the full path to exec.Command().

like image 394
Claudiu S Avatar asked Nov 19 '14 16:11

Claudiu S


People also ask

Can I run Python code in Go?

Python can get embedded as a shared library into programs written in other languages. Here's a trivial example for executing Python code in a Golang program and exchanging data between the two runtimes.

How do I run a .PY file?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do I run a external Python script in flask?

To run the app outside of the VS Code debugger, use the following steps from a terminal: Set an environment variable for FLASK_APP . On Linux and macOS, use export set FLASK_APP=webapp ; on Windows use set FLASK_APP=webapp . Navigate into the hello_app folder, then launch the program using python -m flask run .


1 Answers

Did you try adding Run() or Output(), as in:

exec.Command("script.py").Run()
exec.Command("job.sh").Run()

You can see it used in "How to execute a simple Windows DOS command in Golang?" (for Windows, but the same idea applies for Unix)

c := exec.Command("job.sh")

if err := c.Run(); err != nil { 
    fmt.Println("Error: ", err)
}   

Or, with Output() as in "Exec a shell command in Go":

cmd := exec.Command("job.sh")
out, err := cmd.Output()

if err != nil {
    println(err.Error())
    return
}

fmt.Println(string(out))
like image 146
VonC Avatar answered Sep 29 '22 11:09

VonC