Created
April 17, 2021 06:43
-
-
Save Tokubara/2f351eacbef5b2240cb4fafa719b88f6 to your computer and use it in GitHub Desktop.
jupyter notebook的.ipynb格式的转换脚本
This file contains 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
# 希望, jc a.ipynb, 得到a_ipynb.R, -f或者--format, 指定是得到md | |
# 反过来, jc a_ipynb.R能得到a.ipynb | |
# {{{1 全局变量 | |
format=python # 默认是python | |
target_filename="" | |
# {{{1 print_usage | |
print_usage() { | |
cat <<- EOF | |
usage:jc [-f|--format r|md|py(=py)] filename | |
EOF | |
exit 0 | |
} | |
# {{{1 parge_arg: 得到format(就是可以直接用的format)和filename | |
function parse_arg { | |
# echo "enter parse_arg" | |
while (($#)) | |
do | |
case "$1" in | |
-f|--format) | |
format="$2" | |
get_format | |
shift 2 | |
;; | |
-h|--help) | |
print_usage | |
;; | |
*) | |
filename="$1" | |
shift | |
;; | |
esac | |
done | |
} | |
# {{{1 get_format: 处理format参数, md转换为markdown, py转换为python, r转换为R | |
function get_format() { | |
case $format in | |
py) | |
format=python | |
;; | |
r|R) | |
format=R | |
;; | |
md) | |
format=markdown | |
;; | |
*) | |
echo "get_format:Not support this format" | |
print_usage | |
;; | |
esac | |
} | |
# {{{1 get_target_filename: 得到目标文件名, 应在get_format调用后再调用 | |
function get_target_filename { | |
local extension="" | |
local basename=${filename%.*} | |
case $format in | |
python) | |
extension=py | |
;; | |
R) | |
extension=R | |
;; | |
markdown) | |
extension=md | |
;; | |
*) | |
echo "get_target_filename:Not support this format" | |
print_usage | |
;; | |
esac | |
target_filename=${basename}_ipynb.${extension} | |
} | |
# {{{1 execute: 根据参数文件名的后缀执行相应的命令 | |
function execute { | |
# echo "enter execute" | |
extension=${filename##*.} # 扩展名 | |
case $extension in | |
ipynb) | |
get_target_filename | |
python -m jupytext --to $format --output ${target_filename} ${filename} | |
return 0 | |
;; | |
r|R) | |
format=R | |
;; | |
md) | |
format=markdown | |
;; | |
py) | |
format=python | |
;; | |
*) | |
echo "execute: Not support this format" | |
print_usage | |
;; | |
esac | |
# 反过来, jc a_ipynb.R能得到a.ipynb | |
target_filename=${filename%_ipynb*}.ipynb | |
python -m jupytext --test -x ${target_filename} --to ${format} | |
} | |
parse_arg $@ | |
execute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
其实本来就是一条命令可以搞定的事, 相当于节省一点参数..