[Python]サブプロセス操作[subprocess.run()]

Pythonでsubprocessライブラリを用いて、新しいプロセスを起動して外部コマンドを実行を行うためのサンプルコード一覧

基本

import os,sys
import json
import subprocess
import shutil

#--exe info---
1_exe = "python test.py "
1_file = "test.csv "
1_dir = []
2_exe = "python test2.py"

#--input info--

print("---Select X---")
print("1:AAA")
print("2:BBB")
print("3:CCC")
print("-----------------")
in_X = input("X:")
print("---Select Y---")
print("1:AAA")
print("2:BBB")
print("---------------------")
in_Y = input("Y:")
print("---Select Z---")
print("1:AAA")
print("2:BBB")
print("---------------------")
in_Z = input("Z:")

#--select info--
X = []
Y = ["zero", "AAA", "BBB"]
Z = ["zero", "AAA", "BBB"]

if len(in_X) != 1:
    for i in range(len(in_X)):
        X.append(in_X[i])
else:
    X.append(in_X)

print(X)
print(Y[int(in_Y)])
print(Z[int(in_Z)])

#--set info--

dir_path = './test3'
directories = [name for name in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, name))]

#--read json info---

test_json = 'sample.json'
with open(test_json, 'r', encoding='UTF-8') as f:
    data = json.load(f)
print(data['A'][Y[int(in_Y)]][Z[int(in_Z)]]['id'])

#--run subprocess---

for i in range(len(mode)):

    if X[i] == "1":
        for j in range(len(directories)):
            cmd = 1_exe + 1_file + directories[j]
            subprocess.run(cmd.split())
            if not os.path.exists(directories[j]):
                os.mkdir(directories[j])
            shutil.move("./"+directories[j], "./sample")
    elif X[i] == "2":
        cmd = 2_exe
        subprocess.run(cmd.split())
タイトルとURLをコピーしました