목적
- 첫째 리눅스의 단순 명령어 입력 노가다를 자동화 하기위함
- 디렉토리 생성후 기본 파일을 생성하고자 할때(예 .gitkeep)
- Dockerfile에서 기본 디렉토리를 만들때 유용할 것으로 보임
사용 라이브러리 및 모듈
- os : 운영체제의 일반적인 기능들이 내장된 빌트인 라이브러리
- shutil : 디렉토리안 파일이 들어 있어도 삭제를 하기 위함
- fire : cli로 명령어를 처리 하기 위함
코드
import os
import shutil
import fire
class Dir():
@staticmethod
def get_cur_path(path=None):
return os.getcwd() if path is None else path
def mkdir(self, parentdir=None, names=None, file=None):
print("디렉토리: 생성을 진행하겠습니다. ")
print("디렉토리를 생성하고자하는 부모 디렉토리", parentdir)
print(f"생성하고자 하는 디렉토리: {names}")
if not names:
print("파라미터를 다시 입력하여주세요.")
cwd = Dir.get_cur_path(parentdir)
for dir_name in names:
if not Dir.path_exist_or_not(dir_name):
file_path = os.path.join(cwd, dir_name)
os.mkdir(file_path)
self.mkfile(file_path, file)
print("디렉토리 생성 완료")
def rmdir(self, names):
print("디렉토리: 삭제를 진행하겠습니다. ")
print(f"삭제하고자 하는 디렉토리: {names}")
if not names:
print("파라미터를 다시 입력하여주세요.")
cwd = os.getcwd()
try:
for dir_name in names:
if Dir.path_exist_or_not(dir_name):
abs_path = os.path.join(cwd, dir_name)
shutil.rmtree(abs_path)
print("디렉토리 삭제 완료")
except OSError:
print('디렉토리 삭제중 오류가 발생했습니다.')
@staticmethod
def path_exist_or_not(dir_name):
return os.path.exists(dir_name)
def mkfile(self, path, file=".gitkeep"):
file = ".gitkeep" if file is None else file
with open(f"{path}/{file}", 'w') as fp:
pass
def mkfiles(self, names):
sep = Dir.seperator()
file_list = names.split(sep)
if not file_list:
print("파일을 다시 입력해주세요.")
path = Dir.get_cur_path()
for file in file_list:
self.mkfile(path, file)
@staticmethod
def seperator(name=','):
return name if name is not None else ','
if __name__ == "__main__":
fire.Fire(Dir)
예시
$ python fire_test.py mkdir --names=test1,test2,test3,test4,test5 --file=.gitkeep
디렉토리: 생성을 진행하겠습니다.
생성하고자 하는 디렉토리: ('test1', 'test2', 'test3', 'test4', 'test5')
디렉토리 생성 완료
$ tree -a -L 2 test*
test.ipynb [error opening dir]
test1
└── .gitkeep
test2
└── .gitkeep
test3
└── .gitkeep
test4
└── .gitkeep
test5
└── .gitkeep
$ python fire_test.py rmdir --names=test1,test2,test3,test4,test5
디렉토리: 삭제를 진행하겠습니다.
삭제하고자 하는 디렉토리: ('test1', 'test2', 'test3', 'test4', 'test5')
디렉토리 삭제 완료
$ tree -a -L 2 test*
test.ipynb [error opening dir]
0 directories, 0 files