简体   繁体   English

如何在 Go 中使用 Python 模块中的变量?

[英]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:如:

range.py范围.py

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:])

main.go主.go

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)
}

Output global variables Output 全局变量

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.

相关问题 如何使变量在 Python(和 Qt)中的函数之外可用 - How do I make variables available outside of functions in Python (and Qt) 如何从 Python 的主模块中获取变量? - How do I get variables from my main module in Python? 使用Flask和Angular,如何使$ scope变量可用于python函数 - With Flask and Angular, how do I make $scope variables available to a python function 如何使子模块的类在父模块的命名空间中可用? - How do I make classes from a submodule available in a parent module's namespace? Python:我应该如何使实例变量可用? - Python: How should I make instance variables available? 如何使用 tkinter 模块使用在 Python 的“条目”中输入的变量创建一个按钮来执行和显示计算? - How do I make a button to execute and display calculation using variables entered in “Entry” in Python using the tkinter module? 如何在 Python 中将变量从模块传递到模块? - How can I pass variables from module to module in Python? 如何使应用程序在线可用? [Python] - How do I make an app available online? [Python] 如何使动态导入的模块在另一个模块或文件中可用? - how do I make a dynamically imported module available in another module or file? 如何从 selenium go 对 discord 做出响应 - How do I make response from selenium go onto discord
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM