如何用Go代码获取Windows系统默认浏览器路径?
问题
尝试编写Go代码获取Windows系统默认浏览器路径,在终端执行以下命令可正常得到结果:
for /f "tokens=3" %a in ('reg QUERY HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.html\UserChoice /v ProgId') do reg QUERY HKCR\%a\shell\open\command
执行结果:
(Default) REG_SZ "C:\Program Files\Google\Chrome\Application\chrome.exe" --single-argument %1
但用Go代码实现时:
func main() { var c *exec.Cmd c = exec.Command("cmd", "for /f \"tokens=3\" %a in ('reg QUERY HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.html\\UserChoice /v ProgId') do reg QUERY HKCR\\%a\\shell\\open\\command") if output, err := c.CombinedOutput(); err != nil { fmt.Println("Error: ", err) } else { fmt.Println(string(output)) } }
运行后只得到系统版本信息,无法获取默认浏览器路径,请问如何解决?
解决方法
问题出在两个关键细节上:
- 缺少cmd执行参数:调用
cmd执行命令时,必须添加/c参数,告知cmd执行完指定命令后直接退出,否则只会启动cmd交互环境,不会执行目标命令。 - 批处理变量转义错误:终端直接执行for循环用
%a,但在通过cmd调用的批处理命令中,循环变量需要写成%%a才能被正确解析。
修正后的Go代码如下:
package main import ( "fmt" "os/exec" ) func main() { c := exec.Command("cmd", "/c", `for /f "tokens=3" %%a in ('reg QUERY HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.html\UserChoice /v ProgId') do reg QUERY HKCR\%%a\shell\open\command`) output, err := c.CombinedOutput() if err != nil { fmt.Printf("执行错误: %v\n", err) return } fmt.Println(string(output)) }
如果需要直接提取浏览器路径而非完整的注册表输出,可以在代码中对返回的字符串做进一步解析,比如截取REG_SZ后的内容,去除引号和后续启动参数即可。
内容的提问来源于stack exchange,提问作者Mohammed Dalloul
相关产品推荐
相关产品推荐

