Paramiko raising 'TypeError: catching classes that do not inherit from BaseException is not allowed' at the end of a script that uses `sftp.file/open`

Paramiko raising 'TypeError: catching classes that do not inherit from BaseException is not allowed' at the end of a script that uses `sftp.file/open`

我正在编写一个脚本来获取服务器中的 CSV 文件并将其复制到 PostgreSQL table 中。我找不到解决 Paramiko 在复制文件时引发的错误的方法。我不太明白这个错误,我也没有找到可以帮助我解决这个问题的相关帖子。

SFTP 连接运行良好,数据库远程访问也运行良好,这是有问题的代码块:

try:
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp = transport.open_sftp_client()
    print("SFTP Client : Open")
except Exception as e:
    msg = "Error connecting via ssh: %s" % e
    raise paramiko.SSHException(msg)

XT = "*.csv"
for filename in sftp.listdir(SSH_DIR):
    print(filename,'if-found')

    print("entered loop")
    path = '/%s/%s' % (SSH_DIR, filename)
   
    fobj = sftp.file(os.path.join(SSH_DIR,filename), 'rb')
    print(fobj)
    cur.execute('TRUNCATE TABLE %s' % TABLE_NAME)
    sql = "COPY %s FROM STDIN WITH DELIMITER AS ','  csv header"
    table = 'my_table'
    cur.copy_expert(sql=sql % table, file=fobj)
    conn.commit()

transport.close()

这里是执行脚本时出现的错误

Database connected...
SSH connection succesful
SFTP Client : Open
kpis_inventory_analysis.csv if-found
entered loop
<paramiko.sftp_file.SFTPFile object at 0x7f0369d81f28>
Exception ignored in: <bound method SFTPFile.__del__ of <paramiko.sftp_file.SFTPFile object at 0x7f0369d81f28>>
Traceback (most recent call last):
  File "/home/ubuntu/myenv/lib/python3.6/site-packages/paramiko/sftp_file.py", line 76, in __del__
  File "/home/ubuntu/myenv/lib/python3.6/site-packages/paramiko/sftp_file.py", line 108, in _close
TypeError: catching classes that do not inherit from BaseException is not allowed

非常感谢对此问题的任何帮助

我猜是因为你没有关闭SFTP文件导致的。当 Python 垃圾在脚本末尾收集表示未关闭的 SFTP 文件的 Paramiko 对象时,它失败了,因为底层 SFTP 连接已经关闭。

确保在停止使用后关闭该文件:

    with sftp.file(SSH_DIR + "/" + filename, 'rb') as fobj:
        print(fobj)
        cur.execute('TRUNCATE TABLE %s' % TABLE_NAME)
        sql = "COPY %s FROM STDIN WITH DELIMITER AS ','  csv header"
        table = 'my_table'
        cur.copy_expert(sql=sql % table, file=fobj)

旁注:不要对 SFTP 路径使用 os.path.join。 SFTP 路径需要使用正斜杠。而 os.path 使用本地系统分隔符。