请把文件内的perl代码翻译为python3.7
时间: 2024-10-08 10:19:19 浏览: 28
该Perl脚本主要实现了如下功能:连接数据库并执行SQL查询;处理查询结果中的特定字段,包括清洗和格式化等操作;以及写入新的文件中并创建控制文件。以下是其Python 3.7版本的主要逻辑:
首先需要安装一些依赖库,如`pyodbc`用于数据库连接,使用`os`, `time`, `re`等标准库来完成其它的功能需求。
```python
import os
import re
import pyodbc
from datetime import datetime
# 初始化环境变量
ETLVAR = os.getenv('AUTO_ETLVAR')
AUTO_HOME = os.getenv('AUTO_HOME')
ARGS = ['control_file']
DSN = os.getenv('AUTO_DSN')
# 日期提取
TX_DATE = ARGS[0][-8:] if len(ARGS[0]) >= 8 else ARGS[0][-12:-4]
# 操作系统相关配置
DIRDELI = '\\' if os.name == 'nt' else '/'
JOINFLAG = '�' # 或者用逗号代替
INTERVAL = 1
OBJPATH = f'{AUTO_HOME}{DIRDELI}DATA{DIRDELI}receive'
FILENAME = f'L_ETS_FC_ANA_{TX_DATE}.txt'
ERRORFILE = f'{AUTO_HOME}{DIRDELI}backup{DIRDELI}error{DIRDELI}ETFC_Err{TX_DATE}.log'
# 创建错误日志文件
with open(ERRORFILE, 'w') as FILEERR:
pass
def get_time(format_str):
now = datetime.now()
return now.strftime(format_str)
def db_connect():
PWD_FILE = f"{AUTO_HOME}{DIRDELI}etc{DIRDELI}{TD_LOGON}.txt"
with open(PWD_FILE, 'r') as PF_H:
LOGONKEY = PF_H.read().strip()
TD_USERNAME, TD_PASSWORD = TD_LOGON, LOGONKEY
TD_PASSWORD = os.popen(f'{AUTO_HOME}{DIRDELI}bin{DIRDELI}IceCode.exe -d "{TD_PASSWORD}" "{TD_USERNAME}"').read().strip()
conn = pyodbc.connect(f'DSN={DSN};UID={TD_USERNAME};PWD={TD_PASSWORD}', autocommit=True)
return conn
def remove_str(result, remove_str):
pos_dash = result.find(remove_str)
while pos_dash != -1:
result = result[:pos_dash] + result[pos_dash+len(remove_str):]
pos_dash = result.find(remove_str)
return result
def remove_date(result):
MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
for month in MONTHS:
tmpid = result.find(month)
while tmpid != -1:
if tmpid > 1 and re.match(r'^\d\d$', result[tmpid+3:]):
result = result[:tmpid-2] + result[tmpid+5:]
elif re.match(r'^\d$', result[tmpid-1]):
result = result[:tmpid-1] + result[tmpid+5:]
else:
result = result[:tmpid] + result[tmpid+5:]
tmpid = result.find(month)
return result
def process_data(conn):
sql = """
SELECT top 6 Ticket_NoID, Ticket_No, 1, Fare_Cal_Item
FROM prd_edw.TKT_R8_FARE_CALCULATION_H
WHERE startdt='2012-01-02' AND EndDt=CAST(? AS DATE FORMAT 'YYYYMMDD');
"""
cursor = conn.cursor()
cursor.execute(sql, TX_DATE)
with open(os.path.join(OBJPATH, FILENAME), 'w') as w1, open(ERRORFILE, 'a') as err:
for row in cursor.fetchall():
process(row, w1, err)
def process(row, w1, err):
ticket_id, ticket_no, fare_info = row[0], row[1], row[3]
if 'END' not in fare_info:
err.write(f'{ticket_id},{ticket_no},{fare_info}')
return
fare_info = fare_info[:fare_info.index('END')]
# 更多处理...
# 注意上述仅提供了框架性转换,具体细节可能需进一步调整以匹配原始Perl逻辑。
process_data(db_connect())
```
注意:以上提供的代码仅为一个基本框架,具体的字符串处理逻辑还需按照原Perl程序的复杂规则进行详细实现。例如日期删除逻辑、金额累加等功能都需要进一步细化编写。此外,对于数据库连接及查询的部分,这里假定了数据库驱动和登录凭证的获取方式,实际部署时应按实际情况调整。
阅读全文