[英]How do I make variables from a Python module available in Go?
I am building a tool in Go which needs to provide a way to resolve variables declared in the global scope of Python scripts.我正在 Go 中构建一个工具,它需要提供一种方法来解析在 Python 脚本的全局 scope 中声明的变量。 In the future I would like to extend this to Node.js as well.将来我也想将其扩展到 Node.js。 It needs to be cross-platform.它需要是跨平台的。
Basically, if someone were to have the following Python code:基本上,如果有人有以下 Python 代码:
#!/usr/bin/env python
hello = "world"
some_var = "one"
another_var = "two"
var_three = some_func()
I would like to have access to these variable keys and values in my Golang code.我想在我的 Golang 代码中访问这些变量键和值。 In case of the function, I would like to have access to the value it returns.对于 function,我想访问它返回的值。
My current idea is to run the script with the Golang exec.Command
function and have the variables printed to its stdout in some format (eg JSON), which in turn can be parsed with Golang.我目前的想法是使用 Golang exec.Command
function 运行脚本,并将变量以某种格式(例如 JSON)打印到其标准输出,然后可以使用 Golang 解析。 Thoughts?想法?
They are of different runtime environments.它们属于不同的运行时环境。 Golang cannot directly access variables in Python's runtime. Golang 不能直接访问 Python 运行时中的变量。 Vica versa.反之亦然。 You can, however, program them to pass on variable values through standard I/O or environment variables.但是,您可以对它们进行编程以通过标准 I/O 或环境变量传递变量值。 The key is to determine the proper format for information exchanges.关键是确定信息交换的正确格式。
For example, if the python script takes arguments as input and print the result, encoded as JSON, to the stdout.例如,如果 python 脚本将 arguments 作为输入并将编码为 JSON 的结果打印到标准输出。 Then you can call the script with proper arguments, and decode the stdout as JSON.然后您可以使用正确的 arguments 调用脚本,并将标准输出解码为 JSON。
Such as:如:
import json
import sys
def toNum(str):
return int(str)
def main(argv):
# Basically called range() with all the arguments from script call
print(json.dumps(list(range(*map(toNum, argv)))))
if __name__ == '__main__':
main(sys.argv[1:])
package main
import (
"encoding/json"
"fmt"
"log"
"os/exec"
)
func pythonRange(start, stop, step int) (c []byte, err error) {
return exec.Command(
"python3",
"./range.py",
fmt.Sprintf("%d", start),
fmt.Sprintf("%d", stop),
fmt.Sprintf("%d", step),
).Output()
}
func main() {
var arr []int
// get the output of the python script
result, err := pythonRange(1, 10, 1)
if err != nil {
log.Fatal(err)
}
// decode the stdout of the python script
// as a json array of integer
err = json.Unmarshal(result, &arr)
if err != nil {
log.Fatal(err)
}
// show the result with log.Printf
log.Printf("%#v", arr)
}
To output global variables in Python as JSON object:到 output 全局变量 Python 为 JSON ZA8CFDE6331BD59EB2666F8911ZB4:
import json
def dump_globals():
# Basically called range() with all the arguments from script call
vars = dict()
for (key, value) in globals().items():
if key.startswith("__") and key.endswith("__"):
continue # skip __varname__ variables
try:
json.dumps(value) # test if value is json serializable
vars[key] = value
except:
continue
print(json.dumps(vars))
foo = "foo"
bar = "bar"
dump_globals()
Output: Output:
{"foo": "foo", "bar": "bar"}
You can use a main() similar to the last one for this script:您可以为此脚本使用类似于最后一个的 main():
import (
"encoding/json"
"fmt"
"log"
"os/exec"
)
func pythonGetVars() (c []byte, err error) {
return exec.Command(
"python3",
"./dump_globals.py",
).Output()
}
func main() {
var vars map[string]interface{}
// get the output of the python script
result, err := pythonGetVars()
if err != nil {
log.Fatal(err)
}
// decode the json object
err = json.Unmarshal(result, &vars)
if err != nil {
log.Fatal(err)
}
// show the result with log.Printf
fmt.Printf("%#v", vars)
}
Output: Output:
map[string]interface {}{"bar":"bar", "foo":"foo"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.