从bash脚本中检查Python开发文件是否存在

9
我正在创建一个简单的bash脚本用于下载和安装Python Nagios插件。在一些老旧服务器上,脚本可能需要安装子进程模块,因此我需要确保正确的Python-devel文件已经安装。
有没有适当的跨平台方法来检查这些文件呢?希望避免使用rpm或apt。
如果您能告诉我如何从Python内部进行检查,那就太好了。谢谢!
更新:
这是我能想到的最佳方法。有人知道更好或更可靠的方法吗?
if [ ! -e $(python -c 'from distutils.sysconfig import get_makefile_filename as m; print m()') ]; then echo "Sorry"; fi

你为什么不喜欢RPM呢? - ajreal
2
我需要确定发行版并运行rpm和dpkg(apt)等价物。因此,如果可能的话,我宁愿不要所有那些代码。如果我可以在bash脚本中只做一些类似于“python -c import development-stuff”的事情,并检查退出状态,那就更好了。 - CarpeNoctem
3个回答

6
那就是我处理它的方式。看起来相当简单。
然而,如果我需要确保当前Python版本安装了python-devel文件,我会寻找相关的Python.h文件。大致如下:
# first, makes sure distutils.sysconfig usable
if ! $(python -c "import distutils.sysconfig.get_config_vars" &> /dev/null); then
    echo "ERROR: distutils.sysconfig not usable" >&2
    exit 2
fi

# get include path for this python version
INCLUDE_PY=$(python -c "from distutils import sysconfig as s; print s.get_config_vars()['INCLUDEPY']")
if [ ! -f "${INCLUDE_PY}/Python.h" ]; then
    echo "ERROR: python-devel not installed" >&2
    exit 3
fi

注意:`distutils.sysconfig` 可能不受所有平台支持,因此并非最具可移植性的解决方案,但仍比尝试适应 `apt`、`rpm` 等变化更好。
如果您确实需要支持所有平台,那么探索 AX_PYTHON_DEVEL m4 模块中所做的工作可能是值得的。这个模块可以在 `configure.ac` 脚本中使用,在基于 autotools 的构建的 `./configure` 阶段中并入对 `python-devel` 的检查。

谢谢,我已经修改了脚本以包括Python.h部分! - CarpeNoctem

2

在我看来,你的解决方案很有效。

另外,更加“优雅”的解决方案是使用一个小脚本,例如:

testimport.py

#!/usr/bin/env python2

import sys

try:
  __import__(sys.argv[1])
  print "Sucessfully import", sys.argv[1]
except:
  print "Error!"
  sys.exit(4)

sys.exit(0)

使用testimport.sh distutils.sysconfig来调用它

如有需要,您可以将其调整为检查内部函数...


2

对于那些寻找纯Python解决方案且适用于Python3的人:

python3 -c 'from distutils.sysconfig import get_makefile_filename as m; from os.path import isfile; import sys ; sys.exit(not isfile(m()))')

或者作为文件脚本 check-py-dev.py

from distutils.sysconfig import get_makefile_filename as m
from os.path import isfile 
import sys 
sys.exit(not isfile(m()))

要在Bash中获取一个字符串,只需使用退出输出:
python3 check-py-dev.py && echo "Ok" || echo "Error: Python header files NOT found"

我觉得你的第一个代码块有一个多余的 ) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接