Getting a PHP configuration variable in Go

huangapple go评论100阅读模式
英文:

Getting a PHP configuration variable in Go

问题

我想获取命令 php -r 'echo get_cfg_var("some_var");' 的输出结果,以便与预定义的值进行比较。目前,我有以下代码:

variableName := "default_mimetype"
cmd := exec.Command("php", "-r", "'echo get_cfg_var(\"" + variableName + "\");'")
out, err := cmd.CombinedOutput()

运行后,

err.Error() 返回 "exit status 254"

out 返回 "PHP Parse error: syntax error, unexpected end of file in Command line code on line 1"

是什么导致了这个错误?我没有正确转义某些内容吗?

英文:

I want to get the output of the command php -r 'echo get_cfg_var("some_var");' to check it against a predefined value. Currently, I have the following code:

variableName := "default_mimetype"
cmd := exec.Command("php", "-r", "'echo get_cfg_var(\"" + variableName + "\");'")
out, err := cmd.CombinedOutput()

after running,

err.Error() returns "exit status 254"

out is "PHP Parse error: syntax error, unexpected end of file in Command line code on line 1"

What is causing this error? Am I not escaping something properly?

答案1

得分: 5

问题出在你的参数上。如果你将你写的内容转换成一个shell命令,它会像下面这样:

$ php -r 'echo get_cfg_var("default_mimetype");'

你会注意到第二个参数周围有一对额外的引号,这导致了语法错误。你可以通过将exec.Command更改为以下内容来修复这个问题:

cmd := exec.Command("php", "-r", "echo get_cfg_var(\"" + variableName + "\");")
英文:

The problem is your argument. If you change what you have written into a shell command, it would look like the following:

$ php -r "'echo get_cfg_var(\"default_mimetype\");'"

You will notice that there is an extra set of quotes around the 2nd argument that is causing the syntax error. You can fix this by changing your exec.Command to the following:

cmd := exec.Command("php", "-r", "echo get_cfg_var(\"" + variableName + "\");")

huangapple
  • 本文由 发表于 2015年6月17日 02:53:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/30875893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定