IT TIP

파이썬에서 '어떤'동등한 기능

itqueen 2020. 11. 22. 21:01
반응형

파이썬에서 '어떤'동등한 기능


which abc명령 을 실행하여 환경을 설정해야합니다 . which명령 과 동등한 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()파이썬에 2.4+


나는 이것이 오래된 질문이라는 것을 알고 있지만 Python 3.3 이상을 사용하는 경우 shutil.which(cmd). 여기 에서 설명서를 찾을 수 있습니다 . 표준 라이브러리에 있다는 장점이 있습니다.

예는 다음과 같습니다.

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

이를 수행하는 명령은 없지만 반복 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

행운을 빕니다!


( 비슷한 질문 )

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

을 사용하면 shell=True명령이 시스템 셸을 통해 실행되며 경로에서 바이너리를 자동으로 찾습니다.

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

이는 파일이 존재하는지뿐만 아니라 실행 가능한지 확인하는 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

다음은 이전 답변의 한 줄 버전입니다.

import os
which = lambda y: next(filter(lambda x: os.path.isfile(x) and os.access(x,os.X_OK),[x+os.path.sep+y for x in os.getenv("PATH").split(os.pathsep)]),None)

이렇게 사용 :

>>> which("ls")
'/bin/ls'

참고 URL : https://stackoverflow.com/questions/5226958/which-equivalent-function-in-python

반응형