Python マクロファイルを複製して実行するスクリプトの雛形コード

 本コードの実行例を示します。下図中の「do.py」が本プログラムで、それ以外の「macroA.py」「macroB.py」「macroC.py」がオリジナルのマクロ(スクリプト)ファイルとします。

f:id:HK29:20200405221501p:plain

本プログラムを実行すると下図のように、マクロ(スクリプト)ファイルを複製します。

f:id:HK29:20200405221607p:plain

下図左が、オリジナルファイルで、右が複製後のファイルです。@で囲まれた箇所を置換しています。

f:id:HK29:20200405220648p:plain

下図はファイル複製後に実行した様子です(この例ではprint出力してるだけ)

f:id:HK29:20200405220728p:plain

■本プログラム

# -*- coding: utf-8 -*-
import os, sys, glob
import codecs
import pathlib
import shutil
import subprocess

def initialize():
    if os.path.isdir(save_dir_name):
        shutil.rmtree(save_dir_name)
    os.mkdir(save_dir_name)
    
    for f in glob.glob("derive*"):
        os.remove(f)

def replace_and_run(i, input_path):
    num = str(i)
    dir_num = str("{0:03d}".format(i))
    output_path = 'derive_' + pathlib.PurePath(input_path).stem + '_' + num + pathlib.PurePath(input_path).suffix
    
    shutil.copy2(input_path, output_path)
    with codecs.open(input_path, "r", encoding='shift-jis', errors='ignore') as f2:
        with codecs.open(output_path, "w", encoding='shift-jis', errors='ignore') as f1:
            for row in f2:
                buf = row.replace("@MY_ROW@", dir_num) \
                         .replace("@MY_row@", num) \
                         .replace("@MY_PATH@", dirpath)
                f1.write(buf)
    cmd = command + output_path
    print(cmd)
    run_cmd = subprocess.check_output(cmd.split()) # splitメソッドでリストで与える
    print(run_cmd)

def main():
    global dirpath
    
    # 初期化
    initialize()
    # 再帰的にフォルダを探索する
    for dirpath, dirnames, fnames in os.walk(r'C:\\'):
        # 指定したディレクトリが見つかった段階で抜ける。dirpathは絶対パス
        if (not 'TRASH' in dirpath) and (target_dir_name in dirpath):
            print('dirpath:', dirpath)
            break

    for macro_path in macro_path_list:
        if flag == 'A':
            for i in range(*target_num_range):
                replace_and_run(i, macro_path)
        else:
            for i in target_num_list:
                replace_and_run(i, macro_path)
    
if __name__ == '__main__':
    target_dir_name = 'ProgramData'
    macro_path_list = ['macroA.py', 'macroB.py', 'macroC.py']
    command = 'python ' #'start Excel.exe '
    save_dir_name = 'dirJpg'
    
    flag = 'A'
    target_num_range = [7, 12] # flag A [start, end]
    target_num_list = [1, 5, 10] # flag B
    
    main()
    print("finished")
    

以上

<広告>