Golang中如何创建等效的setup脚本

Golang中如何创建等效的setup脚本 我是Go语言世界的新手,目前正在将一段Python代码转换为Go语言。

以下是Python的安装脚本

import subprocess
import setup, Extension

class buildallC(Command):

def run(self):
print(“Running all C files”)
subprocess.call([‘gmake’, ‘-C’, ‘network-anomaly/Make/gcc’])
subprocess.call([‘gmake’, ‘-C’, ‘network-interface/Make/gcc’])

pynetwork = Extension(manifest.pynetwork, [ ‘pynetwork/pynetwork.cpp, pynetwork/checknetwork.cpp,],
libs=[‘gnutls’],
mydirs = [‘pynetwork’,’network-anomaly/include’,‘network interface/include’,’/usr/local/include’],
thecc=[‘network-anomaly/Make/gcc/lib/libnetwork-anomaly.a’,'network-interface/Make/gcc/lib/libnetwork-interface.a’]

setup(
name=‘SampleTest’,
version=‘2.0’,
packages=[‘SampleTest’],
ext_modules=[pynetwork],
class={
‘buildcprog’: buildallC,
}
)

执行方式:python setup.py buildcprog

如何在Go中执行这部分代码? subprocess.call([‘gmake’, ‘-C’, ‘network-anomaly/Make/gcc’]) subprocess.call([‘gmake’, ‘-C’, ‘network-interface/Make/gcc’]) pynetwork = Extension(manifest.pynetwork, [ ‘pynetwork/pynetwork.cpp, …


更多关于Golang中如何创建等效的setup脚本的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

我使用了 exec.Command(“gmake”,“C”,“network-anomaly/Make/gcc”),看起来运行正常。

func main() {
    fmt.Println("hello world")
}

更多关于Golang中如何创建等效的setup脚本的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我对这个问题的回答取决于另一个问题的答案:你究竟想做什么?这段Python代码看起来是在构建C Python模块。你真的只是想用Go重写这个安装脚本来构建C Python模块吗?如果是这样,我想问:“为什么?”如果你已经安装了Python来使用这些Python模块,为什么不继续使用Python呢?

如果你问的是如何替换C Python模块和/或使用这些模块的Python代码,我们需要看看你试图替换的具体代码部分,然后才能给你建议。

首先,我主要尝试构建并调用位于 network-anomalynetwork-interfacepynetwork 文件夹下的 .c 文件。

如何在 Go 中执行这部分内容? subprocess.call([‘gmake’, ‘-C’, ‘network-anomaly/Make/gcc’]) subprocess.call([‘gmake’, ‘-C’, ‘network-interface/Make/gcc’]) pynetwork = Extension(manifest.pynetwork, [ ‘pynetwork/pynetwork.cpp, …

我尚未开发的主要 Go 代码需要调用上述文件夹中的库,而不是重新开发它们。

在Go中创建等效的setup脚本,可以使用os/exec包执行外部命令,并结合go build机制。以下是完整的Go实现:

package main

import (
    "fmt"
    "os"
    "os/exec"
    "path/filepath"
)

// 构建C库的函数
func buildCLibraries() error {
    fmt.Println("Running all C files")
    
    // 构建第一个C库
    cmd1 := exec.Command("gmake", "-C", "network-anomaly/Make/gcc")
    cmd1.Stdout = os.Stdout
    cmd1.Stderr = os.Stderr
    if err := cmd1.Run(); err != nil {
        return fmt.Errorf("failed to build network-anomaly: %v", err)
    }
    
    // 构建第二个C库
    cmd2 := exec.Command("gmake", "-C", "network-interface/Make/gcc")
    cmd2.Stdout = os.Stdout
    cmd2.Stderr = os.Stderr
    if err := cmd2.Run(); err != nil {
        return fmt.Errorf("failed to build network-interface: %v", err)
    }
    
    return nil
}

// 创建cgo编译配置
func createCGoConfig() string {
    return `//go:build cgo
// +build cgo

package main

/*
#cgo CFLAGS: -Ipynetwork -Inetwork-anomaly/include -Inetwork-interface/include -I/usr/local/include
#cgo LDFLAGS: -Lnetwork-anomaly/Make/gcc/lib -Lnetwork-interface/Make/gcc/lib -lnetwork-anomaly -lnetwork-interface -lgnutls
#include "pynetwork/pynetwork.h"
#include "pynetwork/checknetwork.h"
*/
import "C"
`
}

// 生成Go包装代码
func generateGoWrapper() error {
    wrapperCode := `package main

import (
    "unsafe"
)

// Go wrapper functions for C library
func CheckNetwork() bool {
    return C.check_network() != 0
}

func PyNetworkInit() unsafe.Pointer {
    return unsafe.Pointer(C.pynetwork_init())
}

func PyNetworkProcess(ptr unsafe.Pointer, data []byte) int {
    return int(C.pynetwork_process((*C.pynetwork_t)(ptr), (*C.char)(unsafe.Pointer(&data[0])), C.int(len(data))))
}
`
    
    return os.WriteFile("network_wrapper.go", []byte(wrapperCode), 0644)
}

func main() {
    // 解析命令行参数
    if len(os.Args) < 2 {
        fmt.Println("Usage: go run setup.go buildcprog")
        os.Exit(1)
    }
    
    command := os.Args[1]
    
    switch command {
    case "buildcprog":
        // 构建C库
        if err := buildCLibraries(); err != nil {
            fmt.Printf("Error building C libraries: %v\n", err)
            os.Exit(1)
        }
        
        // 生成cgo配置文件
        cgoConfig := createCGoConfig()
        if err := os.WriteFile("cgo_config.go", []byte(cgoConfig), 0644); err != nil {
            fmt.Printf("Error creating cgo config: %v\n", err)
            os.Exit(1)
        }
        
        // 生成Go包装器
        if err := generateGoWrapper(); err != nil {
            fmt.Printf("Error generating Go wrapper: %v\n", err)
            os.Exit(1)
        }
        
        // 构建Go项目
        cmd := exec.Command("go", "build", "-o", "SampleTest", "-tags", "cgo")
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        if err := cmd.Run(); err != nil {
            fmt.Printf("Error building Go project: %v\n", err)
            os.Exit(1)
        }
        
        fmt.Println("Build completed successfully")
        
    default:
        fmt.Printf("Unknown command: %s\n", command)
        os.Exit(1)
    }
}

对于C扩展的等效实现,创建pynetwork_bridge.go

// pynetwork_bridge.go
package main

// #cgo CFLAGS: -Ipynetwork -Inetwork-anomaly/include -Inetwork-interface/include -I/usr/local/include
// #cgo LDFLAGS: -Lnetwork-anomaly/Make/gcc/lib -Lnetwork-interface/Make/gcc/lib -lnetwork-anomaly -lnetwork-interface -lgnutls
// #include "pynetwork/pynetwork.h"
// #include "pynetwork/checknetwork.h"
import "C"
import (
    "unsafe"
)

// PyNetwork 结构体包装
type PyNetwork struct {
    ptr unsafe.Pointer
}

// NewPyNetwork 创建新的PyNetwork实例
func NewPyNetwork() *PyNetwork {
    return &PyNetwork{
        ptr: unsafe.Pointer(C.pynetwork_init()),
    }
}

// Process 处理网络数据
func (p *PyNetwork) Process(data []byte) int {
    if len(data) == 0 {
        return 0
    }
    return int(C.pynetwork_process((*C.pynetwork_t)(p.ptr), (*C.char)(unsafe.Pointer(&data[0])), C.int(len(data))))
}

// CheckNetwork 检查网络状态
func CheckNetwork() bool {
    return C.check_network() != 0
}

// Cleanup 清理资源
func (p *PyNetwork) Cleanup() {
    C.pynetwork_cleanup((*C.pynetwork_t)(p.ptr))
}

创建go.mod文件定义模块:

module SampleTest

go 1.21

require (
    // 添加必要的依赖
)

执行方式:

# 构建C库并编译Go项目
go run setup.go buildcprog

# 或者直接构建
go build -tags cgo -o SampleTest

这个实现使用os/exec执行gmake命令,通过cgo集成C/C++代码,并提供了与Python Extension类等效的Go包装器。

回到顶部