繁体   English   中英

Python(paramiko)-没有这样的文件或目录:u'\\ u012f \\ u016​​1-test.xls'

[英]Python (paramiko) - No such file or directory: u'\u012f\u0161-test.xls'

我的文件名是这个file_path=u'įš-test.xls

当我尝试这个:

from xlrd import open_workbook
wb = open_workbook(file_path)

我收到此错误:

  File "/usr/local/lib/python2.7/dist-packages/xlrd/__init__.py", line 394, in open_workbook
    f = open(filename, "rb")
IOError: [Errno 2] No such file or directory: u'\u012f\u0161-test.xls'

如果我更改为:

wb = open_workbook(file_path.encode('utf-8'))

IOError: [Errno 2] No such file or directory: '\xc4\xaf\xc5\xa1-test.xls'

注意 paramiko可能有问题,因为使用此方法从远程目录中获取文件(如果具有unicode名称的文件是从本地目录中获取的,它也可以通过):

from contextlib import closing
import socket, os
from paramiko import SSHConfig, SSHClient, AutoAddPolicy, AuthenticationException

    def check_remote_dir(self, cr, uid, ids, direct, arch_dir, gec_type, fmt, context=None):
        rec = self.browse(cr, uid, ids, context=context)[0]
        with closing(SSHClient()) as ssh:
            ssh.set_missing_host_key_policy(AutoAddPolicy())
            try:
                ssh.connect(rec.host, username=rec.user, password=rec.password)
            except socket.gaierror:
               raise orm.except_orm(_('Error!'),
                    _("Name or service '%s' not known") % (rec.host))
            except AuthenticationException:
               raise orm.except_orm(_('Authentication Fail!'),
                    _("Bad username or password"))                    
            with closing(ssh.open_sftp()) as sftp:
                try:
                    sftp.chdir(direct)
                except IOError:
                    raise orm.except_orm(_('Error!'),
                        _('Remote directory %s not found') % (direct)) 
                try:
                    os.chdir(arch_dir)
                except OSError:
                    raise orm.except_orm(_('Error!'),
                        _('Archive directory %s not found') % (arch_dir))                         
                gec_obj = self.pool.get('card.gec.data')
                for f in sftp.listdir():
                    for fmt in fmt.replace(' ', '').split(','): #removing any whitespace and then splitting in list
                        length = len(fmt) + 1
                        if f[-length:] == ".%s" % (fmt):
                            gec_id = gec_obj.create(cr, uid, {'name': f, 'gec_type': gec_type})
                            self._resolve_parse(cr, uid, gec_id, gec_obj, gec_type, f, context=context)
                            self.archive_file(f, None, add_dt=True, remote=True)
                            sftp.remove(f)
                            break #only need to check till first occurence

PS方法参数(例如cr, uid, ids是特定于应用程序的,与远程文件处理并没有真正的关系,因此您可以忽略这些参数

更新我在日志中注意到了这一点:

2015-02-03 10:23:48,143 10430 INFO amb_test paramiko.transport.sftp: [chan 1] Opened sftp connection (server version 3)
is-test.xls
2015-02-03 10:23:48,162 10430 INFO amb_test paramiko.transport.sftp: [chan 1] sftp session closed.

发生这种情况,然后出现该错误。 使用文件之前可能会关闭会话吗?

Update2似乎sftp.listdir() 当我尝试从中使用文件名时,例如使用标准open ,它会出错,因为没有文件,因为我猜它只检查本地目录(我不知道它以前是如何工作的..)。 如果我尝试使用sftp.open()打开,那么它将起作用。

如何使用远程路径在本地服务器中打开它?

远程文件路径似乎出了点问题。 当我得到一个远程路径并尝试直接从该路径打开时,它将看不到它,并且会抛出一个错误,即找不到该文件。

因此,我重写了方法,以不同方式处理远程文件。 现在,它只下载并在本地打开它,而不是远程打开(并且仅在解析后将其保存在本地)。

如果有更好的方法,请随时将其发布为答案。 所以在这里,我的新方法解决了我的问题:

def check_remote_dir(self, cr, uid, ids, rem_dir, local_dir, arch_dir, gec_type, fmt, context=None):
    """
    Only used to check remote directories and download files
    locally
    """
    rec = self.browse(cr, uid, ids, context=context)[0]
    with closing(SSHClient()) as ssh:
        ssh.set_missing_host_key_policy(AutoAddPolicy())
        try:
            ssh.connect(rec.host, username=rec.user, password=rec.password)
        except socket.gaierror:
           raise orm.except_orm(_('Error!'),
                _("Name or service '%s' not known") % (rec.host))
        except AuthenticationException:
           raise orm.except_orm(_('Authentication Fail!'),
                _("Bad username or password"))                    
        with closing(ssh.open_sftp()) as sftp:
            try:
                sftp.chdir(rem_dir)
            except IOError:
                raise orm.except_orm(_('Error!'),
                    _('Remote directory %s not found') % (rem_dir)) 
            try:
                os.chdir(local_dir)
            except OSError:
                raise orm.except_orm(_('Error!'),
                    _('Archive directory %s not found') % (arch_dir))                         
            gec_obj = self.pool.get('card.gec.data')
            for f in sftp.listdir():
                sftp.get(f, f)
                sftp.remove(f)
    #handle files locally
    rec.check_dir(local_dir, arch_dir, gec_type, fmt)  

def check_dir(self, cr, uid, ids, direct, arch_dir, gec_type, formats, context=None):
    rec = self.browse(cr, uid, ids, context=context)[0]
    try:
        os.chdir(direct)
    except OSError:
        raise orm.except_orm(_('Error!'),
            _('Directory %s not found') % (direct))                
    directs = os.listdir(direct)
    gec_obj = self.pool.get('card.gec.data')
    formats = formats.replace(' ', '').split(',') # Removing any whitespace and then splitting in list
    for f in directs:
        for fmt in formats: 
            length = len(fmt) + 1
            if f[-length:] == ".%s" % (fmt):
                gec_id = gec_obj.create(cr, uid, {'name': f, 'gec_type': gec_type})
                self._resolve_parse(cr, uid, gec_id, gec_obj, gec_type, f, context=context)
                self.archive_file(f, arch_dir, add_dt=True)
                break #only need to check till first occurence         

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM