[python] os.system의 출력을 변수에 지정하고 화면에 표시되지 않도록하십시오

사용하는 명령의 출력을 os.system변수 에 할당 하고 화면에 출력되지 않도록하고 싶습니다 . 그러나 아래 코드에서 출력이 화면으로 전송되고 인쇄 된 값 var은 0이며 명령이 성공적으로 실행되었는지 여부를 나타냅니다. 명령 출력을 변수에 할당하고 화면에 표시되지 않도록하는 방법이 있습니까?

var = os.system("cat /etc/services")
print var #Prints 0



답변

“보낸 파이썬에서 강타 역 따옴표의 등가 사용할 수 있습니다 내가 오래 전에 물었다,”입니다 popen:

os.popen('cat /etc/services').read()

로부터 파이썬 3.6 문서 ,

이것은 subprocess.Popen을 사용하여 구현됩니다. 하위 프로세스를 관리하고 통신하는보다 강력한 방법은 해당 클래스의 설명서를 참조하십시오.


다음에 해당하는 코드가 있습니다 subprocess.

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out


답변

또한 subprocess전체 파이썬 popen유형 호출 제품군을 대체하기 위해 작성된 모듈 을 살펴볼 수도 있습니다 .

import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)

이점은 명령을 호출하는 방법, 표준 입 / 출력 / 오류 스트림 등이 연결되는 방식에 유연성이 있다는 것입니다.


답변

명령 모듈은 다음과 같이 상당히 높은 수준의 방법입니다.

import commands
status, output = commands.getstatusoutput("cat /etc/services")

상태는 0이고 출력은 / etc / services의 내용입니다.


답변

Python 3.5 이상 에서는 하위 프로세스 모듈에서 실행 기능 을 사용하는 것이 좋습니다 . 이것은 리턴 CompletedProcess코드뿐만 아니라 출력을 쉽게 얻을 수 있는 오브젝트를 리턴합니다. 출력에만 관심이 있으므로 이와 같은 유틸리티 래퍼를 작성할 수 있습니다.

from subprocess import PIPE, run

def out(command):
    result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
    return result.stdout

my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])


답변

나는 이것이 이미 답변되었다는 것을 알고 있지만 사용 from x import x및 기능을 통해 Popen에 전화하는 더 나은 방법을 공유하고 싶었습니다 .

from subprocess import PIPE, Popen


def cmdline(command):
    process = Popen(
        args=command,
        stdout=PIPE,
        shell=True
    )
    return process.communicate()[0]

print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')
print cmdline('nslookup google.com')


답변

os.system temp 파일로 수행합니다.

import tempfile,os
def readcmd(cmd):
    ftmp = tempfile.NamedTemporaryFile(suffix='.out', prefix='tmp', delete=False)
    fpath = ftmp.name
    if os.name=="nt":
        fpath = fpath.replace("/","\\") # forwin
    ftmp.close()
    os.system(cmd + " > " + fpath)
    data = ""
    with open(fpath, 'r') as file:
        data = file.read()
        file.close()
    os.remove(fpath)
    return data


답변

파이썬 2.6과 3은 특히 stdout과 stderr에 PIPE를 사용하지 말라고 말합니다.

올바른 방법은

import subprocess

# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()

# now operate on the file