How can I run python script and server simultaneously?

How can I get my .go program to run a python script in the background whilst my server runs? It executes the python script first and so it continues to run and therefore doesn’t get round to running the server. FYI, the python script is supposed to record which I aim to stream to the server.

package main

    import (
    	"html/template"
    	"net/http"
    	 "os/exec"
    	 "fmt"
    )

    func handler(w http.ResponseWriter, r *http.Request) {
    	template.Must(template.ParseFiles("test.html")).Execute(w, nil)
    }

    func main() {
    cmd := exec.Command("python","1.py")
    output, err := cmd.Output()

    if (err != nil) {
        fmt.Println(err)
    } 
    fmt.Println(string(output))


    	http.HandleFunc("/", handler)
    	http.Handle("/css/", http.StripPrefix("/css/",
    		http.FileServer(http.Dir("css"))))
    	http.ListenAndServe(":9000", nil)
    }

Many, many thanks!

cmd.Output runs the command until it is completed.

You could run the command in a separate go routine or use cmd.Start.

1 Like

Thanks Nathan, that was the solution:

package main

import (
	"html/template"
	"net/http"
	"os/exec"
	"os"
	"log"
)

func handler(w http.ResponseWriter, r *http.Request) {
	template.Must(template.ParseFiles("test.html")).Execute(w, nil)
}

func main() {
	cmd := exec.Command("python", "test.py")
	cmd.Stdout = os.Stdout
	err := cmd.Start()
	if err != nil {
	  log.Fatal(err)
	}
	log.Printf("Just ran subprocess %d, exiting\n", cmd.Process.Pid)


	http.HandleFunc("/", handler)
	http.Handle("/css/", http.StripPrefix("/css/",
		http.FileServer(http.Dir("css"))))
	http.ListenAndServe(":9000", nil)
}
1 Like

don’t forget to launch a goroutine that would cmd.Wait() the sub-command, otherwise you’d end up with zombies.

(also, it would be probably better to check for the error of both cmd.Wait() and http.ListenAndServe(...).

hth,
-s

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.