Skip to main content
 首页 » 编程设计

python之子进程check_output,Popen,getoutput python之间的区别

2024年10月01日7langtianya

我在 Windows 中使用 python 3.6,我的目标是运行 cmd 命令并将输出作为字符串保存在变量中。 我正在使用子进程及其对象,例如 check_output、Popen and Communicate 和 getoutput。但这是我的问题:

subprocess.check_output 问题是,如果代码返回非零值,则会引发异常,我无法读取输出,例如,执行 netstat -abcd.

stdout_value = (subprocess.check_output(command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=self.timeout)).decode() 

subprocess.Popen 和 communicate() 问题是一些命令,例如 netstat -abcd 从 communicate()< 返回空.

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) 

我想要的是运行任何 cmd 命令(像 netstat 这样的阻塞或像 dir 这样的非阻塞),例如如果用户执行 netstat > 它只显示超时生成的行,然后将其杀死。 谢谢。

编辑------ 根据 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 

请您参考如下方法:

subprocess.run() 超时似乎无法在 Windows 上正常运行。

您可以尝试在 Timer-thread 中运行子进程或者如果你不需要 communicate(),你可以这样做:

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()) 

它适用于 Win7/py3.6 上的所有三个命令,但不适用于 'killed-netstat' 问题!