【问题标题】:'Popen' object is unsubscriptable python 2.6'Popen' 对象是不可订阅的 python 2.6
【发布时间】:2015-07-29 18:23:49
【问题描述】:

我是 Python 新手,不幸的是不知道如何在脚本中操作 vmstat。我有这段代码来获取 vmstat 的输出,经过大量研究后,我无法找到一种方法将其分配为 runqueue1 = sample1[0] 中的变量

    sample1 = Popen(['vmstat'] ,stdout=PIPE, stderr=PIPE)
    stdout, stderr = sample1.communicate()
    stdout.splitlines()[1]
    time.sleep(1)

    sample2 = Popen(['vmstat'] ,stdout=PIPE, stderr=PIPE)
    stdout, stderr = sample2.communicate()
    stdout.splitlines()[1]
    time.sleep(1)


    sample3 = Popen(['vmstat'] ,stdout=PIPE, stderr=PIPE)
    stdout, stderr = sample3.communicate()
    stdout.splitlines()[1]
    time.sleep(1)


    sample4 = Popen(['vmstat'] ,stdout=PIPE, stderr=PIPE)
    stdout, stderr = sample4.communicate()
    stdout.splitlines()[1]
    time.sleep(1)

    sample5 = Popen(['vmstat'] ,stdout=PIPE, stderr=PIPE)
    stdout, stderr = sample5.communicate()
    stdout.splitlines()[1]
    time.sleep(1)


    runqueue1 = sample1[0]
    runqueue2 = sample2[0]
    runqueue3 = sample3[0]
    runqueue4 = sample4[0]
    runqueue5 = sample5[0]

我遇到了这个回溯错误:

Traceback (most recent call last):
   File "./cputool", line 106, in <module>
      cputool()
   File "./cputool", line 98, in cputool
      runqueue1 = sample1[0]
TypeError: 'Popen' object does not support indexing

有没有人建议我如何以不同的方式安排它,以便它可以被索引/下标?除了 popen 之外还有什么其他方法可以获取 vmstat 的值,以便将它们分配给变量?

【问题讨论】:

  • 你想要什么值?例如你期望sample1[0] 会返回什么?如果您正在寻找标准输出,您已经在进一步了解它:stdout, stderr = sample1.communicate()
  • mypipe = os.popen('find.exe . -type f ') myvar = mypipe.readlines()

标签: python indexing popen


【解决方案1】:

这里是一个简短的例子,我希望它能帮助你理解基础知识:

import subprocess
import time

# delay between update in seconds for vmstats
interval = 2
# create the process
proc = subprocess.Popen(
    ['vmstat', str(interval)],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
        try:
                # read operations are *blocking*
                # using readline() instead of read() or readlines()
                # we could start processing a line as soon it is received
                print 'output: %s' % proc.stdout.readline()
        except BaseException, error:
                proc.terminate()
                print 'terminated by %s' % error

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 2012-01-10
    • 2018-04-29
    • 2022-12-11
    • 2023-02-10
    • 2011-05-06
    • 2020-09-07
    • 2023-01-15
    • 1970-01-01
    相关资源
    最近更新 更多