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 脚本了。 我们希望大家觉得本篇文章对您有所帮助。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串