0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

python subprocessで標準出力もエラーもファイル出力する

Posted at

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}"
    print(greeting_sentence)

    # エラーあり
    greeting_sentence = f"僕のニックネームは{nicknames}"
    print(greeting_sentence)

    return greeting_sentence

def test_main():

    greeting_sentence = arg_res()
    print(greeting_sentence)

if __name__=="__main__":
    test_main()


run_greeting.py

import subprocess
from time import time

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

with open('out.txt', 'w') as fp:

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


出力結果

out.txt


僕のニックネームはsmith
僕のニックネームはjohn
僕のニックネームはpower
Traceback (most recent call last):
  File "greeting.py", line 28, in <module>
    test_main()
  File "greeting.py", line 24, in test_main
    greeting_sentence = arg_res()
  File "greeting.py", line 17, in arg_res
    greeting_sentence = f"僕のニックネームは{nicknames}"
NameError: name 'nicknames' is not defined
Traceback (most recent call last):
  File "greeting.py", line 28, in <module>
    test_main()
  File "greeting.py", line 24, in test_main
    greeting_sentence = arg_res()
  File "greeting.py", line 17, in arg_res
    greeting_sentence = f"僕のニックネームは{nicknames}"
NameError: name 'nicknames' is not defined
Traceback (most recent call last):
  File "greeting.py", line 28, in <module>
    test_main()
  File "greeting.py", line 24, in test_main
    greeting_sentence = arg_res()
  File "greeting.py", line 17, in arg_res
    greeting_sentence = f"僕のニックネームは{nicknames}"
NameError: name 'nicknames' is not defined
僕のニックネームはjack
Traceback (most recent call last):
  File "greeting.py", line 28, in <module>
    test_main()
  File "greeting.py", line 24, in test_main
    greeting_sentence = arg_res()
  File "greeting.py", line 17, in arg_res
    greeting_sentence = f"僕のニックネームは{nicknames}"
NameError: name 'nicknames' is not defined



0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?