0

I have a program written in Python (.py) which requires to import and use a function written in Golang (.go) package located in Github repo.

How can I import the .go package module in python code and use the function. The function should accept args from my python code and return a value after doing some operations.

Note: I want to achieve this in Python2.7 version.

go_file.go

// Utility function to get string formed from input list of strings.
func NewFromStrings(inputs []string) string {
    // do something
    return "abc"
}

python_file.py

# This is just a pseudo code to make problem statement more clear.
import github.com/path_to_package/go_file

str_list = ['abc', 'def']
result = go_file.NewFromStrings(str_list)
print(result)

Thanks in advance :)

Sanjit
  • 57
  • 8
  • This is just the reverse of my usecase: https://stackoverflow.com/questions/19397986/calling-python-function-from-go-and-getting-the-function-return-value – Sanjit Jun 12 '22 at 17:36

1 Answers1

0

You have a few options, but it isn't possible to directly import Go code from python without a little work.

  • To do the inverse of the question you linked in your comment, you can create a small go cli to expose your Go function. You can then execute this Go cli from python using subprocess.run. The result will then be accessible from stdout. See https://docs.python.org/3/library/subprocess.html#subprocess.run

  • Alternatively, you can communicate using IPC, like sockets, which will involve creating a little server in Go.

  • The third option I can think of is exporting your Go function in a native library and calling it from python using c bindings. This is probably the most complicated route, but will get you closest to being able to import go code from python.

Check out this blog post with a much more thorough break down of some of your options: https://www.ardanlabs.com/blog/2020/06/python-go-grpc.html

Mulac
  • 33
  • 5