見出し画像

Python経由でPandocを使うと不要な制御コードが付与されないePub3ファイルが作成できる【Pythonコード付き】

 前回作成した↓を使うと1アクションで不要制御コード付きePub3ファイルを制式ePub3ファイルに変換できましたが、これでもその前工程である「PandocでePub3ファイル(不要制御コード付き)を作成」を経ているため2アクションが必要です。

 毎回コマンドを打ったりePub3ファイルを解凍してうんたらかんたらするよりはマシとはいえ面倒なのですべてを1アクションで済ませる、つまり「Python経由でPandocを使ってePub3ファイルに変換し、そのファイルから制式ePub3ファイルを生成」するPythonコードを作成しました。

 ……しかし、動作確認をしている中でPython経由でPandocを使ってePub3ファイルに変換するとなぜか不要制御コードが付かないことに気付きました。原因はさっぱり分かりませんが。

 コードは以下の通り、長く見えますがやっていることはpandoc.exeに各種ファイルを引数で与えているだけです。柔軟な入力ファイル名対応のために長くなっただけで、ファイル名を決め打ちにすればもっと短くできます。

 使い方は適当なファイル名で保存したpyファイルに4ファイル(原稿用テキストファイル(.md or .txt)、スタイルシート(.css)、yamlファイル(.yaml)、表紙用画像ファイル(.jpg or .png))をまとめてドラッグアンドドロップする、もしくは以下のように引数として各種ファイルを指定します。
 pandocのフルパスだけ書き換える必要があります。
 また引数の順番は問いません。なぜなら柔軟性が高いので。

python hogehoge.py main.md style.css meta.yaml cover.jpg

 テキストファイルを同じフォルダにepub3ファイルが出力されます。

import sys
import os
import subprocess
import shutil
import zipfile

#ここだけフルパスで指定要
path_pandoc = "pandoc.exe"

path_css = ""
path_text = ""
path_yaml = ""
path_img = ""
path_output_pandoc_epub3 = ""

def set_by_extension(path_file):
    _, file_ext = os.path.splitext(path_file.lower())
    if file_ext in (".txt",".md"):
        global path_text, path_output_pandoc_epub3
        path_text = path_file
        path_output_pandoc_epub3 = os.path.join(os.path.dirname(path_file),os.path.basename(path_file).split(".")[0]+'_pandoc_output.epub')        
    elif file_ext in (".jpg",".png"):
        global path_img
        path_img = path_file
    elif file_ext in (".yaml"):
        global path_yaml
        path_yaml = path_file
    elif file_ext in (".css"):
        global path_css
        path_css = path_file
    
def convert_to_epub3(path_pandoc, input_text, input_css, input_yaml, input_img, output_epub3):
    pandoc_cmd = [
        path_pandoc, input_text,
        "-o",  output_epub3,
        "--epub-cover-image", input_img,
        "--metadata-file", input_yaml,
        "--css", input_css,
        "-t","epub3","-f","markdown+east_asian_line_breaks","--toc","--toc-depth=3","-N"
        ]   
    try:
        subprocess.run(pandoc_cmd,check=True)
    except FileNotFoundError:
        print("pandoc not found!")

def change_working_directory(path_file):
    os.chdir(os.path.dirname(path_file))

path_files = sys.argv[1:]

for path_file in path_files:
    set_by_extension(path_file)

change_working_directory(path_text)
convert_to_epub3(path_pandoc, path_text, path_css, path_yaml, path_img, path_output_pandoc_epub3)

 以上。


この記事が気に入ったらサポートをしてみませんか?