0

我正在尝试将我的应用程序移植到 Mac,但我不明白是什么导致了这个问题。

在某些时候,我尝试使用 ctypes' 加载第三方提供的几个 C++ 库LoadLibrary。对于 Windows,我有 dll,对于 Mac,我有 dylibs。加载 dylibs 也会产生一个错误,我也在尝试解决这个错误,但这在这里不应该是一个问题,因为我确实有一个 try/except 块来解决这个问题。

try:
    self.log('Lib exists? %s: %s' % (libpath, os.path.exists(libpath)))       
    origdir = os.getcwd()
    os.chdir(os.path.dirname(libpath))
    self.lib = cdll.LoadLibrary(os.path.basename(libpath))
    os.chdir(origdir)
    self.log("Loaded Library!")
except Exception as e:
    self.log('Error importing Library! %s' % e)
    self.lib_loaded = False

任何问题都会写入日志文件。问题是,它以某种方式附加到第一次调用的日志文件中,但在上面的片段中第二次调用时不起作用,在
self.log('Error importing Library! %s' % e).

日志方法很明显:

def log(self, text):
    if self.debug:
        print text
        with open('logfile.log', 'a') as w:
            w.write('%s\n' % text)   

在 Windows 上,这可以正常工作。找到库时,它会加载,当找不到时,我会打印相应的消息并将其写入日志。但在 Mac 上,我得到了错误

Lib exists? /usr/local/lib/path/to/Mylib: True
Error importing Library! dlopen(lib.dylib, 6): no suitable image found.  Did find:
    lib.dylib: mach-o, but wrong architecture
    /usr/local/lib/lib.dylib: mach-o, but wrong architecture
Traceback (most recent call last):
  File "myapp.py", line 987, in <module>
    foo = Foo(pyqtapp, splash)
  File "myapp.py", line 83, in __init__
    self.thelibLink = libLink.libLink(0.05, a, b)
  File "libLink.py", line 100, in __init__
    self.log('Error importing Library! %s' % e)
  File "libLink.py", line 326, in log
    with open(self.logfile, 'a') as w:
IOError: [Errno 13] Permission denied: 'logfile.log'

logfile.log有权限-rw-r--r--并且归我所有,所以这对我来说没有任何意义。此外,运行程序后,日志文件包含以下内容:

==Log of date/time==
Lib exists? /usr/local/lib/path/to/Mylib: True

所以不知何故,我确实有权在self.log第一次调用时附加到文件中。有什么想法可以解决这个问题吗?

4

1 回答 1

3

您正在使用相对路径打开日志文件,但在失败之前更改了目录:

os.chdir(os.path.dirname(libpath))

而是使用绝对路径打开日志文件,因为您显然无法写入os.path.dirname(libpath).

于 2012-10-27T14:29:05.437 回答