我有一个工作中的python脚本(我没有写过),该脚本在一个SQL脚本文件夹中循环,将SQL查询压缩为一行,然后将它们添加到Excel文档(以及其他列)中。这个脚本一直可以正常工作,直到本周我的工作计算机停止工作为止。我得到了一个新的,安装了miniconda,然后通过打开Anaconda提示符并安装了openpyxl:
pip install openpyxl
(pip3安装无效)。
我的大多数Python脚本都能正常工作,但是这一步却不能。它抛出错误:
ImportError: cannot import name 'range' from 'openpyxl.compat' (C:\Users\xxx\AppData\Local\Continuum\miniconda3\lib\site-packages\openpyxl\compat\__init__.py)
我尝试深入研究库/站点包以查看详细信息,并且在该路径的 init 文件中不再看到“范围”。也许他们摆脱了它?有谁知道适合的替代品吗?老实说,我什至不知道它在脚本中的使用位置,但是当我取出该import语句时,它会运行,但是会导致空白的Excel输出文件。很明显,它用在某处
import sqlparse
import glob
import sys
import regex as re
import os
import openpyxl
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.compat import range
def main():
path = "C:/my_path\sql_files*"
fileList = glob.glob(path)
TABLE_ID = 0
# TABLE_NM = ''
# STEP_ID = 0
STEP_TYPE = ''
# workFile = open('C:/Dev\DataWarehouseTesting\workfile.txt', 'w')
# wb = openpyxl.load_workbook('workfile.xlsx')
wb = Workbook()
ws1 = wb.active
ws1.title = "auto_tests"
# Adding the headers for the Excel sheet.
ws1['A1'] = 'TABLE_ID'
ws1['B1'] = 'TABLE_NM'
ws1['C1'] = 'TEST_TABLE_NM'
ws1['D1'] = 'STEP_ID'
ws1['E1'] = 'STEP_TYPE'
ws1['F1'] = 'SQL_SCRIPT'
def createSQL(pTABLE_ID, pTABLE_NM, pTEST_TABLE_NM, pSTEP_ID, pSTEP_TYPE, pSqlStr):
pSqlStr = pSqlStr.replace('\'','"')
sliceLeft = pSqlStr[:6]
if sliceLeft == 'SELECT':
pSTEP_TYPE = 'T'
elif sliceLeft != 'SELECT':
pSTEP_TYPE = 'P'
max_row = ws1.max_row
nextRow = str(max_row + 1)
ws1['A' + nextRow] = str(pTABLE_ID)
ws1['B' + nextRow] = pTABLE_NM
ws1['C' + nextRow] = pTEST_TABLE_NM
ws1['D' + nextRow] = str(pSTEP_ID)
ws1['E' + nextRow] = pSTEP_TYPE
ws1['F' + nextRow] = pSqlStr
def createTableTestSQL(mFile, TABLE_ID, TABLE_NM,STEP_ID, STEP_TYPE):
mText = mFile.read()
mSqls = sqlparse.split(mText)
for mSql in mSqls:
STEP_ID += 1
sqlStr = str(mSql.replace('\n',' '))
sqlStr = re.sub('--([^\s]+)',' ',sqlStr)
sqlStr = sqlparse.format(sqlStr, strip_comments=True)
if STEP_ID == 1:
TEST_TABLE_NM = sqlStr.replace("DROP TABLE ", "").replace(";", "")
createSQL(TABLE_ID, TABLE_NM, TEST_TABLE_NM, STEP_ID, STEP_TYPE, sqlStr)
for filename in fileList:
if filename.endswith('.sql'):
mFile = open(filename,'r')
TABLE_ID += 1
TABLE_NM = os.path.split(filename)[1].replace('.sql','')
#TEST_TABLE_NM = ''
STEP_ID = 0
createTableTestSQL(mFile, TABLE_ID, TABLE_NM, STEP_ID, STEP_TYPE)
mFile.close()
wb.save(filename='test_data_TR.xlsx')
if __name__ == "__main__":
main()