Python 运行脚本错误 OSError: [Errno 8] Exec Format Error

Python 中的 subprocess 模块允许您通过创建新进程来运行命令。 使用其方法运行 shell 脚本时,有时您可能会在 Linux 中遇到 OSError: [Errno 8] Exec format error。

当脚本直接运行而不是通过正确的解释器时,会引发 Exec 格式错误问题。 如果脚本文件的开头没有 shebang 行,则会发生这种情况。

本篇文章将介绍如何修复 Linux 的 OSError: [Errno 8] Exec format error


重现Linux中OSError: [Errno 8] Exec format error 错误

首先,让我们在 Linux 中重现 OSError: [Errno 8] Exec format error

以下是返回 Welcome to Jiyik Tutorials 的 Bash 脚本 myshell.sh。

echo "Welcome to Jiyik Tutorials"

下面是一个 Python 脚本 myscript.py,它使用 subprocess.Popen() 运行上述脚本。

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/jiyik/myshell.sh'

如您所见,它返回错误 OSError: [Errno 8] Exec format error


添加 #!/bin/sh 以修复Linux中 OSError: [Errno 8] Exec format error

解决此问题的最佳方法是在 shell 脚本文件 myshell.sh 的顶部添加 #!/bin/sh。 它确保系统使用正确的解释器来运行 .sh 脚本。

使用任何编辑器编辑 myshell.sh 文件并添加以下行。

#!/bin/sh
echo "Welcome to Jiyik Tutorials"

现在运行 Python 脚本以查看结果。

python3 myscript.py

输出:

Welcome to Jiyik Tutorials

使用 sh 修复Linux 中的 OSError: [Errno 8] Exec format error

您也可以在运行 shell 脚本文件的python 脚本命令中指定 sh

这是一个例子。

import subprocess
shell_file = '/home/jiyik/myshell.sh'
P = subprocess.Popen(['sh', shell_file])

接下来,运行 Python 脚本文件。

python3 myscript.py

输出:

Welcome to Jiyik Tutorials

现在你知道如何在 Linux 中使用 Python 解决 OSError: [Errno 8] Exec format error 和运行 shell 脚本了。 我们希望大家觉得本篇文章对您有所帮助。

猜你喜欢

转载自blog.csdn.net/fengqianlang/article/details/134741280
今日推荐