3

I already checked out Python : Check file is locked and How to check whether a file is_open and the open_status in python. Generally, the following code suits my need, but it doesn't work in Python 2 for Unicode strings.

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)

Any suggestions what I should do?

Community
  • 1
  • 1
Jessie K
  • 93
  • 7

1 Answers1

1

problem solved! Just needed to add a two lines:

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)
Jessie K
  • 93
  • 7
  • there is no reason to reject unicode subclasses: use `isinstance(filename, unicode)` instead of `type(filename) is unicode` (also, I'm not sure it is guaranteed that there is only one `unicode` class instance i.e., you might need `==` instead of `is` here). – jfs Mar 03 '16 at 10:06