【问题标题】:Python program not getting executedPython程序没有被执行
【发布时间】:2021-10-20 04:32:09
【问题描述】:

我在执行 python 程序时遇到错误。有人可以帮我解决这个问题吗?

[root@saas-promethus linuxtest]# /usr/bin/python2 script_azure.py
    Traceback (most recent call last):
      File "script_azure.py", line 43, in <module>
        with connect('HOST', 'user', 'password', 'db') as cur:
    AttributeError: __exit__

Python 代码:

import os, time, json
from itertools import groupby
from MySQLdb import connect
def refresh(cur):
    # Fetch all rows.
    cur.execute("SELECT azure_vm.PrivateIpAddress, azure_vm.VmName, azure_vm.Subnet, azure_vm.ResourceGroupName, azure_vm.VmSize, azure_vm.OsType, azure_vm.Region, azure_vm.subscriptionId, azure_vm.projectName, azure_vm.environmentName, azure_vm.departmentName, azure_vm.applicationName, azure_vm.costCenterName, azure_vm.costCenterCode, azure_app.app FROM azure_vm LEFT JOIN azure_app ON azure_vm.VmId = azure_app.VmId WHERE azure_vm.state !=  'VM Deleted' and azure_vm.Provisioned = 'api_azure' and azure_app.status != 'failed' and azure_app.status != 'removed'")
    tgs = []
    # Group all instances by their job and zone values.
    for key, vals in groupby(cur.fetchall(), key=lambda r: (r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14])):
        tgs.append({
            'labels': dict(zip(['VmName', 'Subnet','ResourceGroupName', 'VmSize', 'OsType', 'Region','SubscriptionId', 'ProjectName', 'Environment', 'DepartmentName', 'ApplicationName', 'CostCenterName', 'CostCeneterCode', 'App'], key)),
            'targets': [t[0] for t in vals],
        })
    # Persist the target groups to disk as JSON file.
    with open('/tgroups/target_groups_azure.json.new', 'w') as f:
        json.dump(tgs, f)
        f.flush()
        os.fsync(f.fileno())
    os.rename('/tgroups/target_groups_azure.json.new', '/tgroups/targets_azure.json')
    sql_select_Query = "SELECT azure_vm.VmId FROM azure_vm LEFT JOIN azure_app ON azure_vm.VmId = azure_app.VmId WHERE azure_vm.state !=  'VM Deleted' and azure_vm.Provisioned = 'api_azure' and azure_app.status != 'failed' or azure_app.status != 'removed'"
    cur.execute(sql_select_Query)
    records = cur.fetchall()
    out=[item for t in records for item in t]
    print(out)
    for i in out:
        manage = "Managed"
        mySql_delete_query = """UPDATE azure_app LEFT JOIN azure_vm ON azure_vm.VmId = azure_app.VmId set azure_app.Monitoring_status = %s WHERE azure_app.VmId = %s and azure_app.status != 'failed' and azure_vm.state != 'VM Deleted' and azure_app.status != 'removed'"""
        inputdata =(manage,i)
        cur.execute(mySql_delete_query,inputdata)
        cur.autocommit = True
if __name__ == '__main__':
    while True:
        with connect('HOST', 'username', 'password', 'database') as cur:
            refresh(cur)
        time.sleep(30)

【问题讨论】:

  • 你能运行这个print(dir(db.connect('HOST', 'username', 'password', 'database')))并在顶部导入并查看输出是否列出了__enter____exit__。由于您在执行命令中使用python2,我不确定MySQLdb.Connection 的python2 版本是否支持上下文处理程序协议。 python3版本确实支持。
  • 不支持带有 connect 的上下文管理器

标签: python compiler-errors


【解决方案1】:

在没有上下文管理器支持的情况下,将代码的最后一部分更改为:

if __name__ == '__main__':
  while True:
    cur = None
    try:
      cur = connect('HOST', 'username', 'password', 'database')
      refresh(cur)
    finally:
      if cur:
        cur.close()
    time.sleep(30)

【讨论】:

    【解决方案2】:

    with connect('HOST', 'username', 'password', 'database') as cur: 可能connect函数的返回对象不支持上下文管理语法

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多