HOWTO · Python
OSError: [Errno 8] Python の Exec フォーマット エラー
このチュートリアルでは、Python で OSError: [Errno 8] Exec format error を修正する方法を説明します。
このページの内容
Python の subprocess モジュールを使用すると、新しいプロセスを作成してコマンドを実行できます。 そのメソッドを使用してシェル スクリプトを実行すると、Linux で OSError: [Errno 8] Exec format error が発生することがあります。
問題 Exec format error は、スクリプトが正しいインタープリターを介さずに直接実行された場合に発生します。 スクリプト ファイルの先頭にシバン行がない場合に発生します。
このチュートリアルでは、Linux の OSError: [Errno 8] Exec format error を修正する方法を説明します。
Linux で OSError: [Errno 8] Exec format error を再作成する
まず、Linux で OSError: [Errno 8] Exec format error を再現してみましょう。
以下は、DelftStack チュートリアルへようこそ を返す Bash スクリプト myshell.sh です。
echo "Welcome to DelftStact Tutorials"
以下は、subprocess.Popen() を使用して上記のスクリプトを実行する Python スクリプト myscript.py です。
import subprocess
shell_file = "/home/delft/myshell.sh"
P = subprocess.Popen(shell_file)
ターミナルで Python スクリプトを実行します。
python3 script.py
出力:
Traceback (most recent call last):
File "myscript.py", line 3, in <module>
P = subprocess.Popen(shell_file)
File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
OSError: [Errno 8] Exec format error: '/home/delft/myshell.sh'
ご覧のとおり、OSError: [Errno 8] Exec format errorというエラーが返されます。
Linux の OSError: [Errno 8] Exec format error を修正するために #!/bin/sh を追加
この問題を解決する最善の方法は、シェル スクリプト ファイル myshell.sh の先頭に #!/bin/sh を追加することです。 これにより、システムが適切なインタープリターを使用して .sh スクリプトを実行することが保証されます。
myshell.sh ファイルを任意のエディターで編集し、以下の行を追加します。
#!/bin/sh
echo "Welcome to DelftStack Tutorials"
次に、Python スクリプトを実行して結果を確認します。
python3 myscript.py
出力:
Welcome to DelftStack Tutorials
sh を使用して、Linux で OSError: [Errno 8] Exec format error を修正する
シェル スクリプト ファイルを実行するコマンドで、Python スクリプトで sh を指定することもできます。
これがその例です。
import subprocess
shell_file = "/home/delft/myshell.sh"
P = subprocess.Popen(["sh", shell_file])
次に、Python スクリプト ファイルを実行します。
python3 myscript.py
出力:
Welcome to DelftStack Tutorials
これで、OSError: [Errno 8] Exec format errorを解決し、Linux で Python を使用してシェル スクリプトを実行する方法がわかりました。 このチュートリアルがお役に立てば幸いです。