windows 如何模拟“锁定”文件(具有写锁的文件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5860542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I simulate a "locked" file (one which has a write lock)
提问by Daisetsu
I am trying to debug a problem where users occasionally have locked files which they try to open. The code appears to have correct exception handling but users are still reporting seeing error messages. How can I simulate a locked file so that I can debug this myself?
我正在尝试调试用户偶尔锁定他们尝试打开的文件的问题。该代码似乎具有正确的异常处理,但用户仍然报告看到错误消息。如何模拟锁定的文件以便我可以自己调试?
EDIT: For Windows.
编辑:对于 Windows。
采纳答案by Luis Siquot
depends, but in case, MS word locks
if you are wonderig if your application lock files and it do not relase locks:
just modify a bit your aplication (to create a testapp) and never close the file (and keep it runnig)
视情况而定,但万一,
如果您想知道您的应用程序是否锁定文件并且它不释放锁定,则 MS 字锁定:
只需修改一点您的应用程序(创建一个测试应用程序)并且永远不要关闭文件(并保持运行)
回答by Zahra
回答by Mayra Delgado
I used LockFileEx function from the Windows API to write a unittest in Python. This worked well for me (shutil.copy() with a locked target fails).
我使用 Windows API 中的 LockFileEx 函数在 Python 中编写单元测试。这对我很有效(shutil.copy() 锁定目标失败)。
import win32con
import win32file
import pywintypes
p = "yourfile.txt"
f = file(p, "w")
hfile = win32file._get_osfhandle(f.fileno())
flags = win32con.LOCKFILE_EXCLUSIVE_LOCK | win32con.LOCKFILE_FAIL_IMMEDIATELY
win32file.LockFileEx(hfile, flags, 0, 0xffff0000, pywintypes.OVERLAPPED())
See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203%28v=vs.85%29.aspx
请参阅:https: //msdn.microsoft.com/en-us/library/windows/desktop/aa365203%28v=vs.85%29.aspx
回答by SpongeB0B
I am using this command prompt
我正在使用这个命令提示符
type yourfile.txt | more
to insert inside yourfile.txt
a very long text of "few pages" and want to pipe via | more
to batch the insertion.
However the file seems to lock, any reason why?
插入yourfile.txt
一个很长的“几页”文本,并希望通过管道| more
批量插入。但是文件似乎锁定了,有什么原因吗?