我有一个 python 脚本,它使用 NetSuite 的 odbc 驱动程序来访问数据库表。我需要每天在特定时间运行这个脚本。我已将此脚本添加到 Ubuntu 服务器上的 crontab 中。
问题是,当我手动运行Python脚本时,它运行成功。 但是当运行 cron 时,它给了我以下错误:
pyodbc.InterfaceError: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')
我不确定问题是什么。 通过 crontab 运行的 bash 脚本如下:
!/bin/bash
source /home/username/Documents/code/.venv/bin/activate
/home/username/Documents/code/.venv/bin/python3 /home/username/Documents/code/odbc.py
手动执行bash脚本时,我是在用户目录下。
username@vm:~$ pwd
/home/username
username@vm:~$ bash .testScript.sh
Python脚本供参考:
import pandas as pd
import pyodbc
import time
import config
import bridge
from datetime import datetime, date
import pandas_gbq
from google.oauth2 import service_account
# GCP Sercice Account credentials for access to BigQuery
credentials = service_account.Credentials.from_service_account_file(
'/home/username/Documents/code/service_account.json',
)
# Establish a ODBC connection
start = time.time()
conn = pyodbc.connect(config.connection_string)
cur = conn.cursor()
end = time.time(
print("Time elapsed: ", end - start)
print("Connection successful, executing query.")
# Tables to import from NetSuite
tables = ["tableName"]
# Loop through all the tables and transfer the data as-is to BigQuery. If the table already exists, replace it with the new one.
for table in tables:
try:
date_today = date.today()
table_name = table
start_time = str(datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z"))
print("Executing loop for table: " + table)
sql = "select * from " + table
start = time.time()
print(datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z"))
data = pd.read_sql(sql,conn)
end = time.time()
print(datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z"))
print("Data read from NetSuite")
pandas_gbq.to_gbq(constdata, "project.dataset." + table, project_id="project", if_exists='replace', credentials=credentials)
end_time = datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z")
status = "Success"
comment = ""
bridge.statusLogger(date_today, table_name, start_time, end_time, status, comment)
except Exception as e:
end_time = str(datetime.now().astimezone(None).strftime("%Y-%m-%d %H:%M:%S GMT%z"))
status = "Error"
comment = str(e)
bridge.statusLogger(date_today, table_name, start_time, end_time, status, comment)
如有任何帮助,我们将不胜感激。
我尝试检查odbc驱动程序是否安装正确。该驱动程序列在 odbcinst.ini 文件中。所以驱动程序存在于系统中。
在你的 bash 脚本下:
/home/username/Documents/code/.venv/bin/python3 /home/username/Documents/code/odbc.py
代替上面的代码,试试这个:
#!/usr/bin/env bash
cd /home/username/Documents/code/
source /home/username/Documents/code/.venv/bin/activate
python odbc.py
我的假设是 pyodbc 安装在该虚拟环境中。 然后,您可以在拥有该代码文件夹及其内部文件的用户下创建 crontab,这样就不会遇到权限问题。