LoginSignup
1
1

More than 1 year has passed since last update.

subprocessを使ってコンソール引数付のpythonファイルを外部から実行する

Posted at

コンソール引数付のファイルを外部から実行する

subpro_qiita.py
import subprocess
from time import time

name_list = ["john","power","smith","jack"]

for i in name_list:
    print(i)
    # コンソール実行時の場合に空白で区切る部分を分割してリストに入れる"
    # python greeting.py --nickname XXXX の場合下記のようになる。
    command = ["python","greeting.py","--nickname", f"{i}"]
    proc = subprocess.Popen(command)

実行するファイル

greeting.py
import argparse
import time

def arg_res():
    parser = argparse.ArgumentParser()
    parser.add_argument('--nickname',required=True)

    args = parser.parse_args()

    nickname = args.nickname

    greeting_sentence = f"僕のニックネームは{nickname}"

    return greeting_sentence

def test_main():

    greeting_sentence = arg_res()
    print(greeting_sentence)

if __name__=="__main__":
    test_main()
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1