exec.Command无法在调试模式下运行

I am trying to use the exec command to create directories in /var and /etc and since I require root permission, I did this:

path := "/var/log/xxx/yyy"
cmd := exec.Command("sudo", "mkdir", "-p", path)
err = cmd.Run()

I am using Visual studio code for my golang projects and interestingly, I found out that this piece of code works really fine when executed from the terminal. But does not work at all when run from visual studio code in the debug mode.

Does anyone know why is this?

I suspect sudo fails to read the password from the terminal, because the debugged process is not connected to a real terminal. Multiple options:

  • Disable password prompt in /etc/sudoers:
%wheel ALL=(ALL) NOPASSWD: ALL
  • Use sudo -A a flag end setup SUDO_ASKPASS environment to a graphical password prompt. For example:
cmd := exec.Command("sudo", "-A", "mkdir", "-p", path)
cmd.Env = append(os.Environ(),
    "SUDO_ASKPASS=/usr/bin/qt4-ssh-askpass")
err := cmd.Run()