2017-11-04 7 views
0

Windows에서 python 3.6을 사용하고 있으며 cmd 명령을 실행하고 결과를 변수에 문자열로 저장합니다. 서브 프로세스와 해당 객체를 check_output, Popen and Communicategetoutput과 같이 사용하고 있습니다. 하지만 여기에 내 문제는 다음과 같습니다.하위 프로세스 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.Popencommunicate() 문제는 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 
+0

...'netstat'에 '내부 버퍼'가있는 것처럼 보입니다. 끝나면 stdout에 쓰여집니다. 'netstat> netstat.log'를 실행할 때 프로세스가 종료되면 아무것도 로그 파일에 기록되지 않습니다. –

+0

@MauriceMeyer 나는 "test.exe"처럼 exe를 실행하려고했지만 EXE 파일을 실행 한 후 시간 초과 후 프로세스를 죽이지는 않는다고 생각합니다. –

답변

2

subprocess.run() Windows에서 제대로 실행되지 않는 것 같습니다.

당신은 Timer-thread 내에서 또는 당신의 경우 서브 프로세스를 실행 시도 할 수 있습니다 해달라고, 당신이 뭔가를 할 수 있습니다) (통신해야합니다 : 그것은 Win7에/py3.6의 모든 세 가지 명령 작동

import time 
import subprocess 

#cmd = 'cmd /c "dir c:\\ /s"' 
#cmd = ['calc.exe'] 
cmd = ['ping', '-n', '25', 'www.google.com'] 

#_stdout = open('C:/temp/stdout.txt', 'w') 
#_stderr = open('C:/temp/stderr.txt', 'w') 

_stdout = subprocess.PIPE 
_stderr = subprocess.PIPE 

proc = subprocess.Popen(cmd, bufsize=0, stdout=_stdout, stderr=_stderr) 

_startTime = time.time() 

while proc.poll() is None and proc.returncode is None: 
    if (time.time() - _startTime) >= 5: 
     print ("command ran for %.6f seconds" % (time.time() - _startTime)) 
     print ("timeout - killing process!") 
     proc.kill() 
     break 

print (proc.stdout.read()) 

, 'kill-netstat'문제는 아닙니다!

+0

대단히 고마워요. –