我需要使用二进制路径设置环境。在外壳中,我可以使用它which来查找路径。python中是否有等效项?这是我的代码。
cmd = ["which","abc"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
res = p.stdout.readlines()
if len(res) == 0: return False
return True
我需要使用二进制路径设置环境。在外壳中,我可以使用它which来查找路径。python中是否有等效项?这是我的代码。
cmd = ["which","abc"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
res = p.stdout.readlines()
if len(res) == 0: return False
return True
Answers:
PATH通过检查该文件where.exe)。
import distutils.spawn。
没有执行此操作的命令,但是您可以遍历environ["PATH"]并查看文件是否存在,这实际上是在which做。
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
祝好运!
os.path.sep代替/和os.pathsep代替:
(类似的问题)
请参见Twisted实现:twisted.python.procutils.which
您可以尝试以下操作:
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
PATHEXT考虑,以及
如果使用shell=True,那么您的命令将在系统外壳中运行,该系统外壳会在路径上自动找到二进制文件:
p = subprocess.Popen("abc", stdout=subprocess.PIPE, shell=True)
shell=True在路径中查找它,但如果要查找存在哪些可能的命令也无济于事。
which它本身也不是检测是否已安装命令的好选择。参考