从bash脚本检查Python开发文件是否存在
我正在写一个简单的bash脚本,用来下载和安装一个Python的Nagios插件。在一些老旧的服务器上,这个脚本可能需要安装subprocess模块,因此我需要确保正确的python-devel文件已经安装。
请问有什么合适且跨平台的方法来检查这些文件呢?我希望能避免使用rpm或apt。
如果你能告诉我怎么在Python内部进行检查,那就太好了,谢谢!
更新:
这是我目前想到的最好办法。有没有人知道更好或更可靠的方法呢?
if [ ! -e $(python -c 'from distutils.sysconfig import get_makefile_filename as m; print m()') ]; then echo "Sorry"; fi
3 个回答
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"
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 来调用它。
如果需要的话,你可以调整它来检查内部函数……
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
脚本中使用,用来在./configure
阶段检查是否安装了python-devel
,这是基于autotools的构建方式。