在Python中,是否有一种可移植且简单的方法来测试可执行程序是否存在?
我说的简单是指像which命令这样完美的命令。我不想手动搜索PATH或涉及尝试与Popen & al执行它,看看它是否失败(这就是我现在做的,但想象它是launchmissiles)
在Python中,是否有一种可移植且简单的方法来测试可执行程序是否存在?
我说的简单是指像which命令这样完美的命令。我不想手动搜索PATH或涉及尝试与Popen & al执行它,看看它是否失败(这就是我现在做的,但想象它是launchmissiles)
当前回答
对于python 3.3及更高版本:
import shutil
command = 'ls'
shutil.which(command) is not None
简·菲利普·格尔克(Jan-Philip Gehrcke)的一句话:
cmd_exists = lambda x: shutil.which(x) is not None
作为一个定义:
def cmd_exists(cmd):
return shutil.which(cmd) is not None
对于python 3.2及更早版本:
my_command = 'ls'
any(
(
os.access(os.path.join(path, my_command), os.X_OK)
and os.path.isfile(os.path.join(path, my_command)
)
for path in os.environ["PATH"].split(os.pathsep)
)
这是Jay的回答中的一行代码,也是一个lambda func:
cmd_exists = lambda x: any((os.access(os.path.join(path, x), os.X_OK) and os.path.isfile(os.path.join(path, x))) for path in os.environ["PATH"].split(os.pathsep))
cmd_exists('ls')
最后,缩进为函数:
def cmd_exists(cmd, path=None):
""" test if path contains an executable file with name
"""
if path is None:
path = os.environ["PATH"].split(os.pathsep)
for prefix in path:
filename = os.path.join(prefix, cmd)
executable = os.access(filename, os.X_OK)
is_not_directory = os.path.isfile(filename)
if executable and is_not_directory:
return True
return False
其他回答
使用Python标准库中的shutil.which()。 电池包括!
一个重要的问题是“为什么需要测试可执行文件是否存在?”也许你不知道?: -)
最近我需要这个功能来启动PNG文件的查看器。我想迭代一些预定义的查看器,并运行第一个存在的查看器。幸运的是,我遇到了os.startfile。好多了!简单,可移植,并使用系统上的默认查看器:
>>> os.startfile('yourfile.png')
更新:关于操作系统我错了。开始文件是可移植的…这是Windows独有的。在Mac上,你必须运行open命令。Unix上的xdg_open。添加Mac和Unix对os.startfile的支持存在Python问题。
这看起来很简单,在python2和python3中都可以使用
try: subprocess.check_output('which executable',shell=True)
except: sys.exit('ERROR: executable not found')
我知道这是一个古老的问题,但是您可以使用distutils.spawn.find_executable。从python 2.4开始就有文档记载,从python 1.6开始就存在了。
import distutils.spawn
distutils.spawn.find_executable("notepad.exe")
此外,Python 3.3现在提供了shutil.which()。
因此,基本上您希望在挂载的文件系统中找到一个文件(不一定只在PATH目录中)并检查它是否可执行。这可以转化为以下计划:
枚举本地挂载的文件系统中的所有文件 用名称模式匹配结果 对于找到的每个文件,检查它是否可执行
我想说,以一种便携式的方式来做这件事将需要大量的计算能力和时间。这真的是你需要的吗?