subprocess.call()의 출력을 취득하고 있습니다.
다음을 사용하여 프로세스 실행 결과를 가져오려면 어떻게 해야 합니까?subprocess.call()
?
패스 aStringIO.StringIO
에 반대하다.stdout
에러가 표시됩니다.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
return Popen(*popenargs, **kwargs).wait()
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 588, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 945, in _get_handles
c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
>>>
Python 버전 > = 2.7을 사용하는 경우 기본적으로 원하는 대로 를 사용할 수 있습니다(표준 출력을 문자열로 반환).
간단한 예(Linux 버전, 참고 참조):
import subprocess
print subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])
ping 명령어는 Linux 표기법을 사용하는 것에 주의해 주세요.-c
(계수용)Windows에서 이 작업을 시도할 경우 로 변경해야 합니다.-n
같은 결과를 얻을 수 있습니다.
아래 코멘트에 기재되어 있는 바와 같이 자세한 설명은 이 답변에서 확인할 수 있습니다.
출력원subprocess.call()
파일에만 리디렉션해야 합니다.
를 사용해 주세요.subprocess.Popen()
대신.그럼 통과해subprocess.PIPE
stderr, stdout 및/또는 stdin 매개변수에 대해 설명하고, 다음을 사용하여 파이프에서 판독합니다.communicate()
방법:
from subprocess import Popen, PIPE
p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
그 이유는 이 파일 같은 오브젝트가subprocess.call()
실제 파일 기술자가 있어야 합니다.따라서,fileno()
방법.파일 같은 오브젝트를 사용하는 것만으로는 문제가 해결되지 않습니다.
자세한 내용은 여기를 참조해 주세요.
python 3.5+의 경우 하위 프로세스 모듈의 실행 기능을 사용하는 것이 좋습니다.그러면 a가 반환됩니다.CompletedProcess
object: 출력 및 리턴 코드를 쉽게 얻을 수 있습니다.
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
다음과 같은 해결책이 있습니다.실행된 외부 명령어의 종료 코드, stdout 및 stderr도 캡처합니다.
import shlex
from subprocess import Popen, PIPE
def get_exitcode_stdout_stderr(cmd):
"""
Execute the external command and get its exitcode, stdout and stderr.
"""
args = shlex.split(cmd)
proc = Popen(args, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
#
return exitcode, out, err
cmd = "..." # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)
여기에도 블로그 투고가 있어요.
편집: 솔루션이 임시 파일에 쓸 필요가 없는 새로운 솔루션으로 업데이트되었습니다.파일을 표시합니다.
최근에 이 작업을 수행하는 방법을 알아냈는데, 현재 진행 중인 프로젝트의 몇 가지 코드 예를 들어 보겠습니다.
#Getting the random picture.
#First find all pictures:
import shlex, subprocess
cmd = 'find ../Pictures/ -regex ".*\(JPG\|NEF\|jpg\)" '
#cmd = raw_input("shell:")
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
#Another way to get output
#output = subprocess.Popen(args,stdout = subprocess.PIPE).stdout
ber = raw_input("search complete, display results?")
print output
#... and on to the selection process ...
이제 명령어의 출력이 "output" 변수에 저장됩니다."stdout = 하위 프로세스입니다.PIPE"는 클래스에게 Popen 내에서 'stdout'이라는 이름의 파일 개체를 생성하도록 지시합니다.communicate() 메서드는 실행한 프로세스의 오류와 출력의 태플을 반환하는 편리한 방법으로 기능합니다.또한 Popen을 인스턴스화할 때 프로세스가 실행됩니다.
중요한 것은 이 기능을 사용하는 것입니다.subprocess.check_output
예를 들어 다음 함수는 프로세스의 stdout과 stderr을 캡처하여 콜의 성공 여부를 반환합니다.Python 2와 3에 대응하고 있습니다.
from subprocess import check_output, CalledProcessError, STDOUT
def system_call(command):
"""
params:
command: list of strings, ex. `["ls", "-l"]`
returns: output, success
"""
try:
output = check_output(command, stderr=STDOUT).decode()
success = True
except CalledProcessError as e:
output = e.output.decode()
success = False
return output, success
output, success = system_call(["ls", "-l"])
명령을 배열이 아닌 문자열로 전달하려면 다음 버전을 사용합니다.
from subprocess import check_output, CalledProcessError, STDOUT
import shlex
def system_call(command):
"""
params:
command: string, ex. `"ls -l"`
returns: output, success
"""
command = shlex.split(command)
try:
output = check_output(command, stderr=STDOUT).decode()
success = True
except CalledProcessError as e:
output = e.output.decode()
success = False
return output, success
output, success = system_call("ls -l")
»Ipython
개요:
In [8]: import subprocess
In [9]: s=subprocess.check_output(["echo", "Hello World!"])
In [10]: s
Out[10]: 'Hello World!\n'
병장의 대답에 근거합니다.병장님의 명예입니다
언급URL : https://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call
'sourcecode' 카테고리의 다른 글
PHP에서 요청 헤더를 읽는 방법 (0) | 2023.01.15 |
---|---|
교육 후 모델을 저장/복원하는 방법 (0) | 2023.01.10 |
Python의 'in' 연산자를 재정의하시겠습니까? (0) | 2023.01.10 |
phpMyAdmin - Error > Invalid format 파라미터? (0) | 2023.01.10 |
문자열 검사기, 파일 이름 (0) | 2023.01.10 |