Last active
August 20, 2019 02:38
-
-
Save jinyu121/7eda53dde76a3c67860662a1a6c23193 to your computer and use it in GitHub Desktop.
C++助教作业辅助脚本:自动生成CMakelists、编译、运行,与CLion兼容
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf8 -*- | |
import os | |
import argparse | |
# 工作目录 | |
working_dir = 'cmake-build-debug' | |
# 被保护的文件 | |
file_protect = ['CMakeLists.txt', 'run.sh', 'data.txt', 'run.py', 'main.py'] | |
# 需要被复制的文件 | |
file_copy = ['data.txt'] | |
# 清理之前的文件 | |
def clean(): | |
for parent, dirnames, filenames in os.walk("./"): | |
if parent == './': | |
for filename in filenames: | |
if filename not in file_protect and filename not in file_copy: | |
os.remove(filename) | |
print("Removed", filename) | |
def doit(): | |
# 只保留需要的文件后缀 | |
using_files = list() | |
for parent, dirnames, filenames in os.walk("./"): | |
if parent == './': | |
for filename in filenames: | |
fnm, fex = os.path.splitext(filename) | |
if fex.lower() in ['.h', '.hpp', '.cpp', '.cxx']: | |
using_files.append(filename) | |
print(using_files) | |
# 使用 enca 进行编码转换 | |
for ext in ['.h', '.hpp', '.cpp', '.cxx', 'txt']: | |
os.system("enca -L zh_CN -x utf-8 *" + ext) | |
# 生成 CMakeList.txt | |
with open("CMakeLists.txt", 'w') as cmake_file: | |
cmake_file.write("cmake_minimum_required(VERSION 3.5)\n") | |
cmake_file.write("project(CPPCourse)\n") | |
cmake_file.write("set(CMAKE_CXX_STANDARD 14)\n") | |
cmake_file.write("set(SOURCE_FILES " + " ".join(using_files) + ")\n") | |
for f in file_copy: | |
cmake_file.write('file(COPY ' + f + ' DESTINATION ./)\n') | |
cmake_file.write("add_executable(CPPCourse ${SOURCE_FILES})\n") | |
# 做一些通用错误的替换 | |
#os.system('sed -i"s/原string/新string/g"文件名') | |
# 更改文件夹 | |
os.chdir('./' + working_dir) | |
# 删除之前的文件 | |
os.system('rm -Rf *') | |
# cmake | |
os.system('cmake -DCMAKE_BUILD_TYPE= -G "CodeBlocks - Unix Makefiles" ../') | |
# make | |
os.system("cmake --build ./ --target all -- -j $(nproc)") | |
# os.system("make all -j 4") | |
# 运行 | |
os.system("cat ../data.txt | ./CPPCourse") | |
# 回到原来的文件夹 | |
os.chdir("../") | |
def runit(): | |
os.system('./' + working_dir + '/CPPCourse') | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--clean', '-c', action='store_true', dest="clean") | |
parser.add_argument('--run', '-r', action='store_true', dest="run") | |
args = parser.parse_args() | |
if args.clean: | |
clean() | |
elif args.run: | |
runit() | |
else: | |
doit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment