如何从 python 脚本检查程序是否存在?
假设您想检查是否wget
or curl
可用。我们假设它们应该在路径中。
最好能看到多平台解决方案,但目前 Linux 就足够了。
Hints:
- 运行命令并检查返回代码并不总是足够的,因为即使您尝试,某些工具也会返回非 0 结果
--version
.
- 检查命令时屏幕上不应显示任何内容
另外,我希望有一个更通用的解决方案,例如is_tool(name)
关闭
让我推荐一个尚未讨论过的选项:Python 实现which
, 具体来说shutil.which https://docs.python.org/3/library/shutil.html#shutil.which。它在Python 3.3中引入,是跨平台的,支持Linux、Mac和Windows。它也可以在 Python 2.x 中通过哪个工艺 https://pypi.python.org/pypi/whichcraft。你也可以直接撕下代码which
就在巫术之外here https://github.com/pydanny/whichcraft/blob/master/whichcraft.py#L20并将其插入到您的程序中。
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
from shutil import which
return which(name) is not None
distutils.spawn.find_executable
已经提到的另一个选项是distutils.spawn.find_executable
.
find_executable
的文档字符串如下:
尝试在“路径”列出的目录中查找“可执行文件”
因此,如果您注意的话,您会注意到该函数的名称有些误导。不像which
, find_executable
实际上并没有验证executable
被标记为可执行文件,只是它位于 PATH 上。所以完全有可能(尽管不太可能)find_executable
表示某个程序可用,而该程序不可用。
例如,假设您有一个文件/usr/bin/wget
未标记为可执行文件。跑步wget
从 shell 中将导致以下错误:bash: /usr/bin/wget: 权限被拒绝. which('wget') is not None
将返回 False,但是find_executable('wget') is not None
将返回 True。您可能可以使用任一功能,但这只是需要注意的事情find_executable
.
def is_tool(name):
"""Check whether `name` is on PATH."""
from distutils.spawn import find_executable
return find_executable(name) is not None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)