Skip to content

Instantly share code, notes, and snippets.

@devstefancho
Last active June 13, 2023 15:22
Show Gist options
  • Save devstefancho/d82f74ba306d2e94c06eef512aaf18a3 to your computer and use it in GitHub Desktop.
Save devstefancho/d82f74ba306d2e94c06eef512aaf18a3 to your computer and use it in GitHub Desktop.
Python script for easy to create, test, submit to leetcode
import subprocess
from enum import Enum
class Command(Enum):
LEETCODE_CLI = "leetcode"
SHOW = "show" # 생성
TEST = "test" # 테스트
SUBMIT = "submit" # 제출
def select_leetcode_command():
commands = [Command.SHOW.value, Command.TEST.value, Command.SUBMIT.value]
p1 = subprocess.Popen(["echo", "\n".join(commands)], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["fzf"], stdin=p1.stdout, stdout=subprocess.PIPE)
output = p2.communicate()[0].strip()
return output.decode()
def select_filename():
# 번호가 있는 파일만 검색
# -print0: 파일이름을 null(\0) 문자로 연결
# xargs -0: null(\0) 문자를 구분자로 사용하여 ls 명령의 인수로 전달
# -t: 최근 수정된 순서로 나열
p = subprocess.Popen(
["find . -name '[0-9]*' -print0 | xargs -0 ls -t | fzf"],
shell=True,
stdout=subprocess.PIPE,
)
output = p.communicate()[0].strip()
return output.decode()
def select_language(lang):
match lang:
case "js":
return "javascript"
case "py":
return "python"
case _:
return "javascript"
def main():
command = select_leetcode_command()
if command == Command.SHOW.value:
number = input("Enter the number: ")
lang = input("Which language(js, py): ")
# -g : generate source file
# -l : choose language
subprocess.run(
[
Command.LEETCODE_CLI.value,
Command.SHOW.value,
number,
"-g",
"-l",
select_language(lang),
]
)
elif command == Command.TEST.value:
filename = select_filename()
subprocess.run([Command.LEETCODE_CLI.value, Command.TEST.value, filename])
elif command == Command.SUBMIT.value:
filename = select_filename()
subprocess.run([Command.LEETCODE_CLI.value, Command.SUBMIT.value, filename])
else:
print("Invalid command number")
exit(1)
# 실행
main()
@devstefancho
Copy link
Author

devstefancho commented Jun 10, 2023

Usage Guide

Prerequisite

Install fzf

brew install fzf

Install leetcode-cli

npm -g install HwangTaehyun/leetcode-cli # should install this repo if you want to use 'leetcode test' command
leetcode version # install other dependencies
leetcode plugin -i cookie.chrome
leetcode user -c # login with chrome cookie (if this not work, login leetcode in vscode then it will make your terminal also logged in
leetcode session # check login status

Run Script

Run this script in your local leetcode file's directory

python3 leetcode-cli.py

Reference

@devstefancho
Copy link
Author

Showcase

showcase-for-leetcode-cli-script.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment