如何使golang执行字符串 [英] how to make golang execute a string

查看:390
本文介绍了如何使golang执行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是要让golang在当前上下文中执行某种评估",只需要它接受输入字符串(例如,从网络接收到的字符串)并将其作为单独的golang程序执行.

I am not asking to make golang do some sort of "eval" in the current context, just need it to take a input string (say, received from network) and execute it as a separate golang program.

理论上,当您运行go run testme.go时,它将把testme.go的内容读入字符串并进行解析,编译和执行.想知道是否可以调用go函数直接执行字符串.请注意,我有一项要求不要将字符串写入文件中.

In theory, when you run go run testme.go, it will read the content of testme.go into a string and parse, compile and execute it. Wonder if it is possible to call a go function to execute a string directly. Note that I have a requirement not to write the string into a file.

UPDATE1

我真的很想找出是否有一个函数(在某些go包中)用作go的入口点,换句话说,我可以使用字符串作为参数来调用此函数,其行为类似于,其中testme.go具有该字符串的内容.

I really want to find out if there is a function (in some go package) that serves as an entry point of go, in another word, I can call this function with a string as parameter, it will behave like go run testme.go, where testme.go has the content of that string.

推荐答案

AFAIK无法完成,并且go编译器必须编写中间文件,因此即使使用go run而不是go build,也会创建文件为了运行代码,必要时将它们清理干净.因此,即使您设法以某种方式使编译器从文件中获取源代码,也无法在不接触磁盘的情况下运行go程序.

AFAIK it cannot be done, and the go compiler has to write intermediate files, so even if you use go run and not go build, files are created for the sake of running the code, they are just cleaned up if necessary. So you can't run a go program without touching the disk, even if you manage to somehow make the compiler take the source not from a file.

例如,在一个简单的hello world程序上调用go run来运行strace时,将显示以下几行内容:

For example, running strace on calling go run on a simple hello world program, shows among other things, the following lines:

mkdir("/tmp/go-build167589894", 0700) 
// ....
mkdir("/tmp/go-build167589894/command-line-arguments/_obj/exe/", 0777) 
// ... and at the end of things
unlink("/tmp/go-build167589894/command-line-arguments/_obj/exe/foo") 
// ^^^ my program was called foo.go
// ....
// and eventually:
rmdir("/tmp/go-build167589894")

因此您可以看到go run在后台进行了大量磁盘写入操作,只是随后进行清理.

So you can see that go run does a lot of disk writing behind the scenes, just cleans up afterwards.

我想如果您愿意的话,您可以挂载一些tmpfs并在其中构建它,但是否则,我认为这是不可能的.

I suppose you can mount some tmpfs and build in it if you wish, but otherwise I don't believe it's possible.

这篇关于如何使golang执行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆