Python中的“等效函数”

我需要运行'which abc'命令来设置环境。 有什么python等效函数的“哪个”命令? 这是我的代码。

cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True 

有distutils.spawn.find_executable 。

我知道这是一个较老的问题,但如果你碰巧使用的是Python 3.3+,你可以使用shutil.which(cmd) 。 你可以在这里find文档。 它具有在标准库中的优点。

一个例子会是这样的:

 >>> import shutil >>> shutil.which("bash") '/usr/bin/bash' 

( 类似问题 )

请参阅Twisted实现: twisted.python.procutils.which

没有一个命令可以这样做,但是你可以迭代environ["PATH"]并查看文件是否存在,这实际上是做什么的。

 import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(path, file) return None 

祝你好运!

你可以尝试如下的东西:

 import os import os.path def which(filename): """docstring for which""" locations = os.environ.get("PATH").split(os.pathsep) candidates = [] for location in locations: candidate = os.path.join(location, filename) if os.path.isfile(candidate): candidates.append(candidate) return candidates 

如果您使用shell=True ,那么您的命令将通过系统shell运行,该shell会自动在path中查找二进制文件:

 p = subprocess.Popen("abc", stdout=subprocess.PIPE, shell=True)