【问题标题】:How to check if a file is R/W locked如何检查文件是否被 R/W 锁定
【发布时间】:2016-03-02 15:42:20
【问题描述】:

我已经签出了Python : Check file is lockedHow to check whether a file is_open and the open_status in python。 通常,以下代码适合我的需要,但它不适用于 Unicode 字符串的 Python 2。

from ctypes import cdll

_sopen = cdll.msvcrt._sopen
_close = cdll.msvcrt._close
_SH_DENYRW = 0x10

def is_open(filename):
    h = _sopen(filename, 0, _SH_DENYRW, 0)
    try:
     return h == -1
    finally:
        _close(h)

有什么建议吗?

【问题讨论】:

  • 文件以 unicode 编码,还是文件名本身是 unicode 字符串?
  • 你收到错误了吗?
  • 类型(文件名)。文件的编码是什么并不重要。
  • 看看_sopen调用了*A()(“ANSI”)win32 API函数,并为Unicode字符串调用了对应的*W(宽)函数。

标签: python file-io unicode msvcrt


【解决方案1】:

问题解决了! 只需要添加两行:

from ctypes import cdll

_sopen = cdll.msvcrt._sopen
_wsopen = cdll.msvcrt._wsopen
_close = cdll.msvcrt._close
_SH_DENYRW = 0x10

def is_open(filename):
    func = _wsopen if type(filename) is unicode else _sopen
    h = func(filename, 0, _SH_DENYRW, 0)
    try:
     return h == -1
    finally:
        _close(h)

【讨论】:

  • 没有理由拒绝 unicode 子类:使用 isinstance(filename, unicode) 而不是 type(filename) is unicode (另外,我不确定是否保证只有一个 unicode 类实例,即你这里可能需要== 而不是is)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多