Python - よく使うモジュール - subprocess コマンド実行

 クラウディア
1. 概要
2. call

1. 概要

 わたしの理解としては・・・、「perl」の「system」みたいなもんだと思っています。  本項は、下記の記事を参考にさせていただきました。
python 上で unix コマンドを実行する - Qiita」
「subprocess --- サブプロセス管理 — Python 3.8.1 ドキュメント」
「【python】os.systemはもう古い!?subprocessでコマンドを実行しよう! | 侍エンジニア塾ブログ(Samurai Blog) - プログラミング入門者向けサイト

2. call

 最も単純な形式らしいのですが・・・。

import subprocess

実行結果 = subprocess.call(コマンド文字列)
 という形式らしい。  実行結果が「0」であれば正常らしい。  下記のようなソースを書いて

result = subprocess.call("whoami")
print(('[whoami]     実行結果['+ str(result) +']'))
print('-------------------------')

result = subprocess.call("echo hello")
print(('[echo hello] 実行結果['+ str(result) +']'))
 実行すると
www
[whoami]     実行結果[0]
-------------------------
Traceback (most recent call last):
  File "/home/hogehoge/lang/python/subprocess/call01.py", line 12, in <module>
    result = subprocess.call("echo hello")
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/subprocess.py", line 389, in call
    with Popen(*popenargs, **kwargs) as p:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/subprocess.py", line 1026, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/local/lib/python3.11/subprocess.py", line 1955, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'echo hello'
 てなことになって、引数をつけるとエラーになっちゃいます。  どうも、1つのコマンドとして解釈するようで・・・。  引数がある場合は、下記のように書きます。

import subprocess

実行結果 = subprocess.call([コマンド文字列, 引数1, 引数2 ...])
 ソースをこう書いて

result = subprocess.call(["echo", "hello"])
print('実行結果['+ str(result) +']')
 実行すると
hello
実行結果[0]
 思った通りの結果が得られました。
earthcar(アースカー)