You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package CommonUtil
import (
"bufio"
"bytes"
"errors"
"log"
"os"
"os/exec"
)
/**
功能: 带回显的执行DOS命令
作者:黄海
时间: 2020-05-18
*/
func Exec ( name string , dir string , args ... string ) error {
cmd := exec . Command ( name , args ... )
stderr , _ := cmd . StderrPipe ( )
stdout , _ := cmd . StdoutPipe ( )
cmd . Dir = dir
if err := cmd . Start ( ) ; err != nil {
log . Println ( "exec the cmd " , name , " failed" )
return err
}
// 正常日志
logScan := bufio . NewScanner ( stdout )
go func ( ) {
for logScan . Scan ( ) {
log . Println ( logScan . Text ( ) )
}
} ( )
// 错误日志
errBuf := bytes . NewBufferString ( "" )
scan := bufio . NewScanner ( stderr )
for scan . Scan ( ) {
s := scan . Text ( )
log . Println ( "" , s )
errBuf . WriteString ( s )
errBuf . WriteString ( "\n" )
}
// 等待命令执行完
cmd . Wait ( )
if ! cmd . ProcessState . Success ( ) {
// 执行失败,返回错误信息
return errors . New ( errBuf . String ( ) )
}
return nil
}
/*
判断文件或文件夹是否存在
如果返回的错误为nil,说明文件或文件夹存在
如果返回的错误类型使用os.IsNotExist()判断为true,说明文件或文件夹不存在
如果返回的错误为其它类型,则不确定是否在存在
*/
func PathExists ( path string ) ( bool , error ) {
_ , err := os . Stat ( path )
if err == nil {
return true , nil
}
if os . IsNotExist ( err ) {
return false , nil
}
return false , err
}