윈도우 vscode 에서 알고리즘 문제 입력 편하게 불러와서 쓰는 방법

이라운·2022년 8월 23일
0
post-thumbnail

❓백준 문제 입력 매번 복붙해서 테스트하기 귀찮다

개발자는 반복작업을 싫어한다.
그런 의미에서 백준 문제 풀 때마다 코드를 복붙해서 집어넣고 테스트하는게 정말 귀찮았다.
내 알고리즘 문제 풀이 디렉토리 구조는 이렇게 생겼다.

sys.stdin = open('Gold/1922.txt', 'r')
input = sys.stdin.readline

그래서 이런 코드를 집어넣어서 같은 폴더안에 동일한 이름의 txt 파일이 있으면 내용을 읽어오게 만들었다.

그런데 이렇게 했더니 저 Gold 라는 폴더명과 1922.txt의 문제 번호 부분을 매번 바꿔서 입력해줘야 했다.
이런 의미없는 반복작업이 싫어서
최종적으로 snippet 을 만들어서 자동으로 같은 이름의 txt 파일을 읽어오게 만들었다.


💡vscode 에서 snippet 만들기

내가 넣고 싶은 자동완성 구문은,
4949.py4949.txt 이렇게 2개의 파일이 있는 상황에서
4949.py 에서 코드를 실행시키면 txt 파일의 내용을 입력받아서 결과를 도출하도록 만드는 것이다.

그럴려면 먼저 snippet 을 만들어줘야 한다.
vscode 를 열고 File > Preferences > Configure User Snippets 로 들어간다.
그러면 아래와 같은 창이 중앙 윗부분에 뜰 것이다.
위의 auto input 뭐시기는 내가 현재 사용중인 사용자 지정 snippet 이다.

두 번째를 클릭하면 vscode 를 사용하는 모든 프로젝트에서 사용할 수 있는 스니펫을 만드는 것이고
세 번째는 현재 내가 작업하고 있는 폴더에서만 동작하는 스니펫을 만드는 것이다.
(현재 작업 폴더이름이 algorithms 여서 file for 'algorithms'라고 나온다)
지금 만드는 스니펫은 알고리즘 풀때말고는 쓸 곳이 없으니 나는 작업폴더에서 만들었다.

세 번째를 클릭하면 아래와 같이 이름을 입력하라고 한다.

난 블로그 포스팅용이므로 대충 test_for_velog 라고 입력하고 enter 를 눌렀다.

그러면 작업 폴더 안에 아래와 같은 폴더와 파일이 생긴다.

(역시나 위는 내가 이전에 만들어서 사용중인 스니펫)

test_for_velog.code-snippets 파일을 클릭하면 아래와 같은 내용이 적혀있다.

{
	// Place your algorithms workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
	// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is 
	// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. 
	// Placeholders with the same ids are connected.
	// Example:
	// "Print to console": {
	// 	"scope": "javascript,typescript",
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
}

💻 코드

위에 뭐 주석 같은건 필요없고

{
	"auto input build": {
		"scope": "python",
		"prefix": "auto",
		"body": [
			"import sys",
			"path = __file__[0:-2] + 'txt'",
			"sys.stdin = open(path, 'r')",
			"input = sys.stdin.readline",
		],
		"description": "input generator for Baekjoon"
	}
}

뜻은 python 언어에서 사용할거고, auto 라는 단어가 입력되면 자동완성 시켜줘, 그 내용을 body 에 적힌거 적어주면 돼.
설명은 백준을 위한 input 생성기. 뭐 이런 뜻이다.
prefix 나 description 은 편한대로 작성해주면 된다.

이렇게 되면 스니펫 생성이 끝난 것이다.
py 파일을 생성하고 prefix 를 입력하면 이렇게 바로 자동완성 추천으로 뜨는 것을 볼 수 있다.

이렇게 코드가 깔끔하게 들어오면 진짜 끝!

그러면 이제 4949.py4949.txt 이렇게 2개의 파일이 같은 폴더안에 있을 때
4949.py 에서 코드를 실행시키면 4949.txt 파일의 내용을 읽어온다.

그럼 다들 즐거운 알고라이프가 되기를😉

profile
Programmer + Poet = Proet

0개의 댓글