无法为python中的变量赋值

时间:2014-11-25 21:28:10

标签: python

我正在尝试从vcenter中提取数据存储区值并执行使用计算,如下所示:

s = VIServer()
s.connect(HOST, USER, PASSWORD)


properties = [  "name",
                "summary.capacity",
                "summary.freeSpace",
             ]

results = s._retrieve_properties_traversal(property_names=properties,
                                           obj_type=MORTypes.Datastore)
d = time.strftime('%Y-%m-%d %H:%M:%S')

for item in results:
    for r in item.PropSet:
                if r.Name == "name" :
                        name = r.Val

    for p in item.PropSet:
        global Total_Space,Free_Space
        if p.Name=="summary.capacity":
                Total_Space=p.Val
                Metric="datastore.space_total"
                print Metric,d,p.Val,"datastore="+name,"source="+"datastore"

        if p.Name=="summary.freeSpace":
                Free_Space=p.Val
                Metric="datastore.space_free"
                print Metric,d,p.Val,"datastore="+name,"source="+"datastore"
        if Total_Space>0 &  Free_Space>0:
                Used_Space=Total_Space-Free_Space
                Used_Percent=(Used_Space/Total_Space)*100

                Metric="datastore.space_used"
                print Metric,d,Used_Space,"datastore="+name,"source="+"datastore"
                Metric="datastore.diskPctUsed"
                print Metric,d,Used_Percent,"datastore="+name,"source="+"datastore"

当我运行时,我收到此错误:

Traceback (most recent call last):
  File "datastore.py", line 41, in <module>
    if Total_Space>0 &  Free_Space>0:
NameError: global name 'Total_Space' is not defined

我有什么想法可以解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

使用您计划的第一个值初始化Total_SpaceFree_Space

Total_Space = 0
Free_Space = 0

答案 1 :(得分:1)

由于您在说'Total_Space'之前未在全球范围内声明global Total_Space,因此您应该全局添加Total_Space = None # or whatever value you like,即在for循环或任何函数之外

答案 2 :(得分:1)

从代码逻辑开始,在 for 循环后检查这些值是有意义的。因此,您将确保初始化并检查一次:

 ...
 Total_Space = 0
 Free_Space = 0
 for p in item.PropSet:
     ...

 if Total_Space and Free_Space:
     ...

但是,如果您将它们初始化为无,则可以在 PropSet 中进一步检查是否存在它们:

 ...
 Total_Space = None
 Free_Space = None
 for p in item.PropSet:
     ...

 if Total_Space == None:
     print "error: no Total_Space in PropSet"
 elif Free_Space == None:
     print "error: no Free_Space in PropSet"
 elif Total_Space and Free_Space:
     ...

有些说明:

  • 您应该使用布尔运算符代替&amp; 作为按位运算符

  • 此外,&amp; higher priority而不是&gt; ,表达式将被评估为

    如果Total_Space&gt; (0&amp; Free_Space)&gt; 0:

  • 在条件句中,如果值而不是,则可以使用,如果值> 0