태그 보관물: Go언어

Go언어 cron 처럼 스케줄링 하기

cron과 같은 유형의 스케줄러는 데이터 처리를 할 때 반드시 필요합니다.

데이터과학자들은 주로 젠킨스(Jenkins)나 airflow를 사용하겠지만 Python이나 Go로 직접 작성해야 하는 경우도 종종 생깁니다.

패키지 “github.com/jasonlvhit/gocron” 를 사용하는 방법입니다.

package main

import (
	"fmt"
	"github.com/jasonlvhit/gocron"
	"time"
)

func task() {
	fmt.Println("태스크를 실행합니다.")
}

func taskWithParams(a int, b string) {
	fmt.Println(a, b)
}

func main() {
	// 파라미터 없이 잡을 실행
	gocron.Every(2).Seconds().Do(task)
	gocron.Every(1).Minute().Do(task)
	gocron.Every(2).Minutes().Do(task)
	gocron.Every(1).Hour().Do(task)
	gocron.Every(2).Hours().Do(task)
	gocron.Every(1).Day().Do(task)
	gocron.Every(2).Days().Do(task)
	gocron.Every(1).Week().Do(task)
	gocron.Every(2).Weeks().Do(task)

	// 파라미터를 지정해서 잡을 실행
	gocron.Every(1).Second().Do(taskWithParams, 1, "hello")

	// 지정한 요일에 잡을 실행
	gocron.Every(1).Monday().Do(task)
	gocron.Every(1).Thursday().Do(task)

	// 지정한 시각에 잡을 실행 - 'hour:min:sec' - seconds optional
	gocron.Every(1).Day().At("10:30").Do(task)
	gocron.Every(1).Monday().At("18:30").Do(task)
	gocron.Every(1).Tuesday().At("18:30:59").Do(task)

	// Begin job immediately upon start
	gocron.Every(1).Hour().From(gocron.NextTick()).Do(task)

	// Begin job at a specific date/time
	t := time.Date(2019, time.November, 10, 15, 0, 0, 0, time.Local)
	gocron.Every(1).Hour().From(&t).Do(task)

	// NextRun은 다음번 실행될 시간을 알려줌
	_, time := gocron.NextRun()
	fmt.Println(time)

	// 지정한 태스크 제거
	gocron.Remove(task)

	// 모든 스케줄 작업을 제거
	gocron.Clear()

	// 모든 펜딩잡을 시작
	<-gocron.Start()

	// 새 스케줄러를 생성해서 동시에 2개의 스케줄러를 실행
	s := gocron.NewScheduler()
	s.Every(3).Seconds().Do(task)
	<-s.Start()
}

Go언어 csv.gz 한줄씩 읽어오기

Go언어로 CSV파일을 한줄씩 읽어오는 방법입니다.

파일을 메모리에 올려서 한 번에 처리하면 파일이 큰 경우에는 메모리를 다 쓰기 때문에 스왑을 사용해서 문제를 만듭니다.

조금 느리더라도 파일은 1줄씩 읽거나 조금씩 읽어야 합니다.

// csv.gz 파일에서 데이터를 한 줄씩 읽어오는 방법
package main

import (
	"compress/gzip"
	"encoding/csv"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
)

func main() {
	file, err := os.Open("product_titles.csv.gz")

	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()

	gzipReader, err := gzip.NewReader(file)

	if err != nil {
		log.Fatal(err)
	}

	defer gzipReader.Close()

	csvReader := csv.NewReader(gzipReader)
	csvReader.Comma = '\t'
	csvReader.FieldsPerRecord = -1

	for {
		record, err := csvReader.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}

		// 첫번째 필드만 꺼내오기
		fmt.Println("record count:", len(record))
		if len(record) < 1 {
			log.Println("record is empty")
			continue
		}
		field1 := strings.Trim(record[0], " ")
		if len(field1) < 1 {
			log.Println("field1 is empty")
			continue
		}

		fmt.Println("field1:", field1)
	}
}

Go언어 CSV 파일 쓰기 – Golang writing a csv file

Go언어로 CSV 파일을 만드는 코드입니다.

데이터 과학 업무를 하다보면 데이터처리를 할 때 CSV 파일을 빈번하게 읽거나 만드는 일이 있습니다.

특히 사이즈가 큰 파일은 처리 속도도 매우 중요하기 때문에 Go나 Rust, C++로 처리해야 할 수 있습니다.

Go언어로 CSV 파일을 처리하는 방법을 알아 두면 그럴 때 편하게 쓸 수 있습니다.

package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

func main() {
	csvFile, err := os.Create("output.csv")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer csvFile.Close()

	records := [][]string{{"item1", "value1"}, {"item2", "value2"}, {"item3", "value3"}}

	writer := csv.NewWriter(csvFile)
	for _, record := range records {
		err := writer.Write(record)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}
	}
	writer.Flush()
}

When you work on data science. you frequently deal with CSV files. and sometimes the CSV files are so big. in that case, processing speed is also important.

So you need to know how can you deal with CSV files with high-performance computer languages like Go, Rust, C++.

Go언어 FastText 모델 로딩해서 예측 수행하기 – Golang do prediction with built model

Facebook FastText로 만든 분류모델 (supervised model)을 로딩해서 prediction하는 간단한 코드입니다.

FastText 모델은 Python으로도 로딩해서 사용할 수 있습니다.

하지만 Python은 멀티쓰레드를 사용하기가 어려우니 빠른 속도를 위해서 Go언어나 다른 언어를 써야 할 때가 있으니 알아두면 좋습니다.

// FastText prediction
package main

import (
	"fmt"
	fasttext "github.com/bountylabs/go-fasttext"
)

func main() {
	model := fasttext.Open("//model/fasttext01.bin")
	fmt.Println("Prediction...")
	predictResult, err := model.Predict("분류할 입력 텍스트입니다.")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("Label: %s, Prob: %fs\n", predictResult[0].Label, predictResult[0].Probability)
}

FastText provide a command-line process to make a model. to apply the model to production, you may want write code for processing particular logic.

so, you need to know how cat load prebuilt FastText model and process prediction with Go language

Go언어 명령행 인수 처리 – Golang getting arguments from command line

Go언어에서 명령행 인수를 처리하는 방법입니다.

몇가지 방법이 더 있지만 여기에서는 flag 모듈를 사용합니다.

package main

import (
	"flag"
	"fmt"
)

func main() {
	file := flag.String("file", "default.txt", "Input file")
	maxcpu := flag.Int("maxcpu", 10, "Max CPU Count")
	isForce := flag.Bool("force", false, "Run force")

	flag.Parse()

	// 포인터 변수이므로 앞에 * 를 붙어 deference 해줘야 한다.
	fmt.Printf("file: %s\n", *file)
	fmt.Printf("maxcpu: %d\n", *maxcpu)
	fmt.Printf("force: %t\n", *isForce)
}

/* 테스트
C> go build exam_arguments.go
C> exam_arguments -file=test.csv -maxtrial=5 -force=true
*/

Go언어 CPU 수 알아내기

Go언어에서 CPU 수를 알아내는 코드입니다.

// OS, 아키텍쳐, CPU수, 고루틴 수를 출력한다.
package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Println("OS\t\t", runtime.GOOS)
	fmt.Println("ARCH\t\t", runtime.GOARCH)
	fmt.Println("CPU\t\t", runtime.NumCPU())
	fmt.Println("Goroutines\t", runtime.NumGoroutine())
}

Go언어 파일 목록 읽기

특정 디렉토리에 있는 파일 목록을 읽어오는 코드입니다.

요점

ioutil.ReadDir 함수를 사용하면 됩니다.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
)

func main() {
	files, err := ioutil.ReadDir("/tmp/")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		fmt.Println(file.Name(), file.IsDir())
	}
}

How to retrieve a list of files from a particular directory.

Use “iotuil.ReadDir”

Go언어 csv.gz 읽기

csv파일은 gzip 압축이 되는 경우가 많습니다.

압축을 따로 풀지않고 gz 압축된 csv 파일을 직접 처리하는 것이 더 편할때가 많아졌습니다.

Go언어에서 gzip으로 압축된 csv 파일을 읽는 방법입니다.

package main

import (
	"compress/gzip"
	"encoding/csv"
	"fmt"
	"log"
	"os"
)

func main() {
	file, err := os.Open("data.csv.gz")

	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()

	gzipReader, err := gzip.NewReader(file)

	if err != nil {
		log.Fatal(err)
	}

	defer gzipReader.Close()

	csvReader := csv.NewReader(gzipReader)
	record, err := csvReader.Read()

	if err != nil {
		log.Fatal(err)
	}

	for _, v := range record {
		fmt.Println(v)
	}
}

윈도우에서 Go언어 개발할 때 Avast 경고메세지 없애기

윈도우에서 Go언어로 개발할 때 Avast를 백신으로 사용하고 있다면 잦은 실행파일을 빌드할 때 마다 검사 경고가뜹니다.

디버깅이나 실행버튼을 누를때마다 이런 일이 일어나기 때문에 굉장히 귀찮고 소리도 무척 거슬립니다.

해결책

Avast의 CyberCapture 기능을 비할성화하면 이 문제가 사라집니다.

주의점

물론 보안상 조금 더 위험해집니다.

작업이 끝나면 원래대로 설정을 바꿔 놓을 수 있습니다.

스크린샷

When developing a Golang application in Windows, how to disable the alert message.

If you develop an application with Golang in the environment which use Avast antivirus for Antivirus solution then you may frequently see alert message from Avast antivirus. for the purpose of removing the alert message.

Solution. You can disable the CyberCapture in your Avast configuration.