2011-03-08 9 views
41

which abc 명령을 실행하여 환경을 설정해야합니다. which 명령과 동일한 기능이 있습니까? 이것은 내 코드입니다.'which is equivalent function in Python

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

도 쉘 자체에서,'which' 자체는 명령이 설치되었는지 여부를 감지하기에 좋은 선택이 아닙니다. [참조] (http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script/677212#677212) – kojiro

답변

61
+5

+1, 이것은 멋진 라이브러리이며 표준 라이브러리의 일부입니다! PATHEXT를 구문 분석하지 않고 대신 '.exe'확장자 (배치 파일 누락)를 검색해야한다고 가정합니다. – orip

+0

Google 검색 결과에서 그만한 가치가 있습니다. –

+2

파일이 실행 가능한지 확인하지 않으므로주의하십시오. – temoto

11

이 그렇게하는 명령 아니지만, 당신은 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 

행운을 빈다!

+1

당신은 pathsep 문자에 대한 가정을 할 때주의하고 싶습니다. . –

+0

과 경로 구분 기호를 사용하지만 점을 찍기가 쉽지 않습니다. 행운을 빕니다! –

+0

':'대신'os.path.sep'를 사용하고':'대신'os.pathsep'를 사용합니다. – djhaskin987

4

당신은 뭔가를 시도 할 수 다음

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 
+0

) PATHEXT도 고려해야한다. – orip

+1

Windows 컴퓨터에서 확장명을 사용하는 것과는 대조적으로 파일의 정확한 이름을 찾습니다. 그 말로는 PATHEXT 멤버를 반복하는 내부 루프를 추가하는 것이 어렵지 않을 것입니다. –

2

, 다음 명령은 시스템을 통해 실행됩니다 셸은 경로상의 바이너리를 자동으로 찾습니다.

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

'shell = True'가 없어도 경로에서 찾았지만 가능한 명령이 있는지 찾으려면 도움이되지 않습니다. –

22

이 질문은 이전 질문이지만, 파이썬 3.3 이상을 사용하는 경우 shutil.which(cmd)을 사용할 수 있습니다. 문서 here을 찾을 수 있습니다. 표준 라이브러리에있는 이점이 있습니다.

예는과 같이 될 것이다 :

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

이의 상당이며, which 명령하는뿐만 아니라 검사 파일뿐만 아니라, 그 실행 여부가있는 경우 :

import os 

def which(file_name): 
    for path in os.environ["PATH"].split(os.pathsep): 
     full_path = os.path.join(path, file_name) 
     if os.path.exists(full_path) and os.access(full_path, os.X_OK): 
      return full_path 
    return None