Python의 Bash Backticks와 동일
Python의 Ruby 및 Perl에서 발견되는 백틱에 해당하는 것은 무엇입니까? 즉, Ruby에서 다음과 같이 할 수 있습니다.
foo = `cat /tmp/baz`
파이썬에서 동등한 문장은 어떻게 생겼습니까? 나는 시도 os.system("cat /tmp/baz")
했지만 결과를 표준에 넣고 해당 작업의 오류 코드를 반환합니다.
output = os.popen('cat /tmp/baz').read()
가장 유연한 방법은 subprocess
모듈 을 사용하는 것입니다 .
import subprocess
out = subprocess.run(["cat", "/tmp/baz"], capture_output=True)
print("program output:", out)
capture_output
Python 3.7에서 도입되었으며, 이전 버전의 경우 특수 함수 check_output()
를 대신 사용할 수 있습니다.
out = subprocess.check_output(["cat", "/tmp/baz"])
세밀한 제어가 필요한 경우 하위 프로세스 개체를 수동으로 생성 할 수도 있습니다.
proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
이러한 모든 함수는 키워드 매개 변수 를 지원 하여 하위 프로세스가 정확히 실행되는 방식을 사용자 정의합니다. 예를 들어 shell=True
파일 이름 확장과 같은 것이 필요한 경우 셸을 통해 프로그램을 실행하는 데 사용할 수 *
있지만 제한이 있습니다.
sth가 맞다 . os.popen ()을 사용할 수도 있지만 가능한 경우 (Python 2.4+) 하위 프로세스가 일반적으로 선호됩니다.
그러나이를 권장하는 일부 언어와 달리 일반적으로 언어 내에서 동일한 작업을 수행 할 수있는 하위 프로세스를 생성하는 것은 잘못된 형식으로 간주됩니다. 느리고 덜 안정적이며 플랫폼에 따라 다릅니다. 귀하의 예는 다음과 같이 더 나을 것입니다.
foo= open('/tmp/baz').read()
eta :
baz는 디렉토리이고 해당 디렉토리에있는 모든 파일의 내용을 가져 오려고합니다.
? 디렉토리의 고양이는 나에게 오류를 가져옵니다.
파일 목록이 필요한 경우 :
import os
foo= os.listdir('/tmp/baz')
디렉토리에있는 모든 파일의 내용을 원하면 다음과 같습니다.
contents= []
for leaf in os.listdir('/tmp/baz'):
path= os.path.join('/tmp/baz', leaf)
if os.path.isfile(path):
contents.append(open(path, 'rb').read())
foo= ''.join(contents)
또는 거기에 디렉토리가 없다고 확신 할 수 있다면 한 줄에 넣을 수 있습니다.
path= '/tmp/baz'
foo= ''.join(open(os.path.join(path, child), 'rb').read() for child in os.listdir(path))
foo = subprocess.check_output(["cat", "/tmp/baz"])
Python 3.5부터 권장되는 방법은 subprocess.run
. 설명하는 것과 동일한 동작을 얻으려면 다음을 사용합니다.
output = subprocess.run("ls", shell=True, stdout=subprocess.PIPE).stdout
이것은 bytes
객체 를 반환 합니다. .decode("ascii")
또는 .decode("utf-8")
끝에 추가 하여 str
.
가장 쉬운 방법은 명령 패키지를 사용하는 것입니다.
import commands
commands.getoutput("whoami")
산출:
'바가 네산'
import os
foo = os.popen('cat /tmp/baz', 'r').read()
나는 사용하고있다
(6 : 0) $ python-버전 Python 2.7.1
위의 예 중 하나는 다음과 같습니다.
import subprocess
proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
나를 위해 이것은 / tmp 디렉토리에 액세스하지 못했습니다. 하위 프로세스에 대한 문서 문자열을 살펴본 후
[ "prog", "arg"]
와
"프로그램 인수"
원하는 쉘 확장 동작을 얻었습니다 (a la Perl의`prog arg`).
print subprocess.Popen("ls -ld /tmp/v*", stdout=subprocess.PIPE, shell=True).communicate()[0]
I quit using python a while back because I was annoyed with the difficulty of of doing the equivalent of perl `cmd ...`. I'm glad to find Python has made this reasonable.
If you use subprocess.Popen, remember to specify bufsize. The default is 0, which means "unbuffered", not "choose a reasonable default".
This will not work in python3, but in python2 you can extend str
with a custom __repr__
method that calls your shell command and returns it like so:
#!/usr/bin/env python
import os
class Command(str):
"""Call system commands"""
def __repr__(cmd):
return os.popen(cmd).read()
Which you can use like
#!/usr/bin/env python
from command import Command
who_i_am = `Command('whoami')`
# Or predeclare your shell command strings
whoami = Command('whoami')
who_i_am = `whoami`
repr()
The backtick
(`) operator was removed in Python 3
. It is confusingly similar to a single quote, and hard to type on some keyboards. Instead of the backtick
, use the equivalent built-in function repr()
.
참고URL : https://stackoverflow.com/questions/1410976/equivalent-of-bash-backticks-in-python
'development' 카테고리의 다른 글
com.android.tools.lint : lint-gradle Android Studio 3을 찾을 수 없습니다. (0) | 2020.10.13 |
---|---|
잠긴 객체는 내부에서 예외가 발생하면 잠긴 상태로 유지됩니까? (0) | 2020.10.13 |
PHP에서 PDF 편집? (0) | 2020.10.12 |
SQL Server에서 쿼리의 텍스트를 어떻게 연결합니까? (0) | 2020.10.12 |
그렇다면 사용자 정의 HTML 속성이 유효한 XHTML이 아니라면 어떻게 될까요? (0) | 2020.10.12 |