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

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

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

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

■本プログラム
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())
print(run_cmd)
def main():
global dirpath
initialize()
for dirpath, dirnames, fnames in os.walk(r'C:\\'):
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 '
save_dir_name = 'dirJpg'
flag = 'A'
target_num_range = [7, 12]
target_num_list = [1, 5, 10]
main()
print("finished")
以上
<広告>
リンク