【问题标题】:difference between subprocess check_output, Popen, getoutput python子进程check_output,Popen,getoutput python之间的区别
【发布时间】:2018-04-16 23:07:58
【问题描述】:

我在 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

【问题讨论】:

  • ...看来netstat 有一个“内部缓冲区”或其他东西,并在完成时写入标准输出?!当执行netstat > netstat.log 并且进程被杀死时,不会将任何内容写入日志文件。
  • @MauriceMeyer 我不这么认为,我尝试像“test.exe”一样运行 exe,但是在运行 exe 文件后,它并没有在超时后终止进程。

标签: python subprocess


【解决方案1】:

subprocess.run() with timeout 在 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”问题!

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 2016-07-10
    • 2018-12-05
    • 2011-10-03
    • 2018-02-21
    相关资源
    最近更新 更多