Windows에서 python 3.6을 사용하고 있으며 cmd 명령을 실행하고 결과를 변수에 문자열로 저장합니다. 서브 프로세스와 해당 객체를 check_output
, Popen and Communicate
및 getoutput
과 같이 사용하고 있습니다. 하지만 여기에 내 문제는 다음과 같습니다.하위 프로세스 check_output, Popen, getoutput python 사이의 차이
subprocess.check_output
코드가 0이 아닌 값을 반환하면 예외가 발생하고 예를 들어 netstat -abcd
을 실행하여 출력을 읽을 수 없습니다.
stdout_value = (subprocess.check_output(command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=self.timeout)).decode()
subprocess.Popen
및 communicate()
문제는 communicate()
에서 빈 netstat -abcd
반환과 같은 몇 가지 명령입니다.
self.process = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
stdin=subprocess.PIPE)
try:
self.process.wait(timeout=5)
stdout_value = self.process.communicate()[0]
except:
self.process.kill()
self.process.wait()
subprocess.getoutput(Command)
괜찮습니다하지만 내 코드가 netstat
같은 몇 가지 명령을 실행에 영원히 차단할 수 있도록 제한 시간이 없다. 또한 스레드로 실행하려고했지만 코드가 블로킹되어 스레드 자체를 멈출 수 없습니다. 내가 원하는 무엇
stdout_value = subprocess.getoutput(command)
은 사용자가 단지 시간 제한에서 생성 된 선이 표시 netstat
를 실행하는 경우, 예를 들어 시간 제한 어떤 cmd를 명령 (같은 dir
같은 netstat
또는 비 차단 차단)를 실행하고 다음을 죽인다. 감사합니다. .
EDIT ------ Jean의 대답에 따르면 코드를 다시 작성했지만 시간 제한이 netstat
과 같은 일부 명령을 실행하는 데 작동하지 않습니다.
# command = "netstat"
command = "test.exe" # running an executable program can't be killed after timeout
self.process = subprocess.run(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
timeout=3,
universal_newlines=True
)
stdout_value = self.process.stdout
...'netstat'에 '내부 버퍼'가있는 것처럼 보입니다. 끝나면 stdout에 쓰여집니다. 'netstat> netstat.log'를 실행할 때 프로세스가 종료되면 아무것도 로그 파일에 기록되지 않습니다. –
@MauriceMeyer 나는 "test.exe"처럼 exe를 실행하려고했지만 EXE 파일을 실행 한 후 시간 초과 후 프로세스를 죽이지는 않는다고 생각합니다. –