osモジュールとsubprocessモジュールを介してシェルコマンドを実行すると、1つは機能し、もう1つは機能しません。

osモジュールとsubprocessモジュールを介してシェルコマンドを実行すると、1つは機能し、もう1つは機能しません。

私はosモジュールとsubprocessモジュールを介してシェルコマンドを実行する方法を学びます。以下は私のコードです。

from subprocess import call
call('/usr/lib/mailman/bin/find_member -w user_email')
import os
os.system('/usr/lib/mailman/bin/find_member -w user_email')

2つ目は完璧に動作しますが、1つ目は機能せず、次のエラーが発生します。

Traceback (most recent call last):
  File "fabfile.py", line 6, in <module>
    call('/usr/lib/mailman/bin/find_member -w user_email')
  File "/usr/lib64/python2.6/subprocess.py", line 478, in call
    p = Popen(*popenargs, **kwargs)
  File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

どちらの方法も同じ効果があると思います。ここで私が間違っていることを指摘してもらえますか?とても感謝しています。

ベストアンサー1

2つの間の1つの違いが文書化されています(ここ)

os.system(コマンド)

サブシェルでコマンド(文字列)を実行します。

しかし、subprocess.call()良い:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

argsで説明されているコマンドを実行します。コマンドが完了するのを待ってからreturncodeプロパティを返します。

アクションを通過する必要があるのと同じにするにはsubprocess.call()。だからこんな感じ:os.system()shell=True

from subprocess import call
call('/usr/lib/mailman/bin/find_member -w user_email', shell=True)

おすすめ記事