/ /シェルスクリプトの実行時のPythonエラー-python、shell、subprocess

シェルスクリプト実行時のPythonエラー - python、shell、subprocess

私はpythonを使用してシェルスクリプトの行を実行しています。 which 自作の存在をテストする

#!/usr/bin/python
import sys, subprocess
subprocess.call(["which python"])

長いエラーをスローします

Traceback (most recent call last):
File "installations.py", line 5, in <module>
subprocess.call(["which python"])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

しかし、シェルの実行が何らかのレベルで正しく動作していることを知っています

#!/usr/bin/python
import sys, subprocess
subprocess.call(["whoami])

ユーザー名が正常に出力されます。私は何か間違ったことをしていますか、それは何らかの理由でサポートされていませんか?インストールの存在を検出する、より良いサポートされた方法はありますか?

回答:

回答№1は4

失敗した呼び出しは、実行されていない「which python」という名前の実行可能ファイルを見つけようとしています which 議論のついた python おそらくあなたが意図したように。呼び出すために渡すリスト(ただし、 shell=True is set)は、コマンドとすべての引数のリストです。やること

subprocess.call(["which", "python"])

おそらくあなたが探しているものを提供します。


回答№2の場合は3

この方法を呼び出す場合、コマンドラインの各単語を反復可能の異なる要素として分離する必要があります。

subprocess.call(["which", "python"])

高く 読むことをお勧めします ドキュメント サブプロセスを起動するすべての可能な方法と、それらが互いにどのように異なるかを真に理解するために、何度か繰り返します。