Hướng dẫn python check if file is open by another process windows - python kiểm tra xem tệp có được mở bởi một cửa sổ quy trình khác không

Trên Windows, bạn cũng có thể truy xuất trực tiếp thông tin bằng cách tận dụng API Windows NTDLL/KERNEL32. Mã sau trả về danh sách các PID, trong trường hợp tệp vẫn được mở/sử dụng bởi một quy trình (bao gồm cả của riêng bạn, nếu bạn có một tay cầm mở trên tệp):Windows, you can also directly retrieve the information by leveraging on the NTDLL/KERNEL32 Windows API. The following code returns a list of PIDs, in case the file is still opened/used by a process (including your own, if you have an open handle on the file):

import ctypes
from ctypes import wintypes

path = r"C:\temp\test.txt"

# -----------------------------------------------------------------------------
# generic strings and constants
# -----------------------------------------------------------------------------

ntdll = ctypes.WinDLL('ntdll')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

NTSTATUS = wintypes.LONG

INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
FILE_READ_ATTRIBUTES = 0x80
FILE_SHARE_READ = 1
OPEN_EXISTING = 3
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000

FILE_INFORMATION_CLASS = wintypes.ULONG
FileProcessIdsUsingFileInformation = 47

LPSECURITY_ATTRIBUTES = wintypes.LPVOID
ULONG_PTR = wintypes.WPARAM


# -----------------------------------------------------------------------------
# create handle on concerned file with dwDesiredAccess == FILE_READ_ATTRIBUTES
# -----------------------------------------------------------------------------

kernel32.CreateFileW.restype = wintypes.HANDLE
kernel32.CreateFileW.argtypes = (
    wintypes.LPCWSTR,      # In     lpFileName
    wintypes.DWORD,        # In     dwDesiredAccess
    wintypes.DWORD,        # In     dwShareMode
    LPSECURITY_ATTRIBUTES,  # In_opt lpSecurityAttributes
    wintypes.DWORD,        # In     dwCreationDisposition
    wintypes.DWORD,        # In     dwFlagsAndAttributes
    wintypes.HANDLE)       # In_opt hTemplateFile
hFile = kernel32.CreateFileW(
    path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, None, OPEN_EXISTING,
    FILE_FLAG_BACKUP_SEMANTICS, None)
if hFile == INVALID_HANDLE_VALUE:
    raise ctypes.WinError(ctypes.get_last_error())


# -----------------------------------------------------------------------------
# prepare data types for system call
# -----------------------------------------------------------------------------

class IO_STATUS_BLOCK(ctypes.Structure):
    class _STATUS(ctypes.Union):
        _fields_ = (('Status', NTSTATUS),
                    ('Pointer', wintypes.LPVOID))
    _anonymous_ = '_Status',
    _fields_ = (('_Status', _STATUS),
                ('Information', ULONG_PTR))


iosb = IO_STATUS_BLOCK()


class FILE_PROCESS_IDS_USING_FILE_INFORMATION(ctypes.Structure):
    _fields_ = (('NumberOfProcessIdsInList', wintypes.LARGE_INTEGER),
                ('ProcessIdList', wintypes.LARGE_INTEGER * 64))


info = FILE_PROCESS_IDS_USING_FILE_INFORMATION()

PIO_STATUS_BLOCK = ctypes.POINTER(IO_STATUS_BLOCK)
ntdll.NtQueryInformationFile.restype = NTSTATUS
ntdll.NtQueryInformationFile.argtypes = (
    wintypes.HANDLE,        # In  FileHandle
    PIO_STATUS_BLOCK,       # Out IoStatusBlock
    wintypes.LPVOID,        # Out FileInformation
    wintypes.ULONG,         # In  Length
    FILE_INFORMATION_CLASS)  # In  FileInformationClass

# -----------------------------------------------------------------------------
# system call to retrieve list of PIDs currently using the file
# -----------------------------------------------------------------------------
status = ntdll.NtQueryInformationFile(hFile, ctypes.byref(iosb),
                                      ctypes.byref(info),
                                      ctypes.sizeof(info),
                                      FileProcessIdsUsingFileInformation)
pidList = info.ProcessIdList[0:info.NumberOfProcessIdsInList]
print(pidList)

Các tập tin được sử dụng để lưu trữ dữ liệu vĩnh viễn. Làm việc với một tệp là một nhiệm vụ rất phổ biến của bất kỳ ngôn ngữ lập trình nào. Nhiều chức năng tích hợp tồn tại trong Python để tạo, mở, đọc, viết và đóng tệp. Hai loại tệp có thể được tạo để lưu trữ dữ liệu. Đây là các tệp văn bản và tệp nhị phân. Bất kỳ tập tin nào được yêu cầu để mở trước khi đọc hoặc viết. Hàm Open () được sử dụng trong Python để mở một tệp. Sử dụng hàm Open () là một cách để kiểm tra một tệp cụ thể được mở hoặc đóng. Nếu hàm Open () mở tệp đã mở trước đó, thì ioError sẽ được tạo. Một cách khác để kiểm tra tệp được mở hoặc đóng là kiểm tra các giá trị của thuộc tính đóng của đối tượng Trình xử lý tệp. Sử dụng hàm đổi tên () là một cách khác để kiểm tra tệp được mở hoặc đóng. Các cách khác nhau để kiểm tra bất kỳ tệp nào được mở hoặc đóng trong Python đã được hiển thị trong hướng dẫn này.open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated. Another way to check a file is opened or closed is to check the values of the closed property of the file handler object. Using rename() function is another way to check the file is opened or closed. Different ways to check any file is opened or closed in Python have been shown in this tutorial.

Tạo một tệp để kiểm tra:

Bạn có thể sử dụng bất kỳ tệp hiện có hoặc tạo tệp mới để kiểm tra mã ví dụ được hiển thị trong hướng dẫn này. Một tệp văn bản mới có tên CLITELL.TXT đã được tạo với nội dung sau để sử dụng sau này trong phần tiếp theo của hướng dẫn.clients.txt has been created with the following content to use later in the next part of the tutorial.

& Nbsp; & nbsp; & nbsp; & nbsp; & nbsp; name & nbsp; & nbsp; & nbsp; & nbsp; email 01 & nbsp; & nbsp; & nbsp; [Email & nbsp; được bảo vệ] 02 & nbsp; & nbsp; & nbsp; & nbsp; nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; [Email & nbsp; được bảo vệ] 05 & nbsp; & nbsp; ]
01     Jony Liver                [email protected]
02     Manik Hossain        [email protected]
03     Neha Akter              [email protected]
04     Janatul Ferdous      [email protected]
05     Helal Uddin             [email protected]

Ví dụ-1: Kiểm tra tệp được mở hoặc không bằng cách sử dụng ioerror

IoError tạo khi hàm open () được gọi để mở một tệp đã được mở trước đó. Tạo một tệp Python với tập lệnh sau để kiểm tra tệp được mở hoặc không bằng cách sử dụng khối Try-Except. Ở đây, bất kỳ tên tệp hiện có sẽ được lấy làm đầu vào và được mở để đọc. Tiếp theo, hàm Open () được gọi lại để mở cùng một tệp sẽ tăng ioError và in thông báo lỗi. generates when the open() function is called to open a file that has been opened before. Create a python file with the following script to check a file is opened or not by using try-except block. Here, any existing filename will be taken as input and opened for reading. Next, the open() function is called again to open the same file that will raise an IOError and print the error message.

# Lấy tên tệp để kiểm tra fileName = input ("Nhập bất kỳ tên tệp hiện có nào: \ n")# Mở tệp lần đầu tiên bằng cách sử dụng hàm Open () fileHandler = open (fileName, "r")# Hãy thử mở tệp tương tự Tệp lại thử: & nbsp; & nbsp; với Open ("FileName", "R") dưới dạng tệp: & nbsp; & nbsp; & nbsp; & nbsp; # In tin nhắn thành công & nbsp; & nbsp; & nbsp; & nbsp; in ("Tệp đã mở để đọc.")# RA RA Lỗi nếu tệp được mở trước đó ngoại trừ ioerror: & nbsp; & nbsp; in ("Tệp đã mở.")
filename = input("Enter any existing filename:\n")
# Open the file for the first time using open() function
fileHandler = open(filename, "r")
# Try to open the file same file again
try:
    with open("filename", "r") as file:
        # Print the success message
        print("File has opened for reading.")
# Raise error if the file is opened before
except IOError:
    print("File has opened already.")

Output:

Đầu ra sau sẽ xuất hiện sau khi thực thi tập lệnh trên. Ở đây, client.txt tồn tại ở vị trí hiện tại và thông báo lỗi, File File đã mở ra, đã được in cho ngoại lệ ioerror.clients.txt exists in the current location, and the error message, “File has opened already,” has printed for the IOError exception.

Hướng dẫn python check if file is open by another process windows - python kiểm tra xem tệp có được mở bởi một cửa sổ quy trình khác không

Ví dụ-2: Kiểm tra tệp được đóng hoặc không bằng cách sử dụng thuộc tính đóng.

Giá trị của thuộc tính đóng sẽ đúng nếu có bất kỳ tệp nào được đóng. Tạo một tệp Python với tập lệnh sau để kiểm tra tệp được đóng hoặc không tồn tại ở vị trí hiện tại. Tập lệnh ví dụ trước sẽ tạo lỗi nếu tên tệp được lấy từ người dùng không tồn tại ở vị trí hiện tại. Vấn đề này đã giải quyết trong ví dụ này. Mô -đun HĐH được sử dụng ở đây để kiểm tra sự tồn tại của tên tệp sẽ được lấy từ người dùng. Hàm Check_closes () đã được xác định để kiểm tra tệp được đóng hoặc không được gọi nếu tệp tồn tại.closed property will be true if any file is closed. Create a python file with the following script to check a file is closed or not that exists in the current location. The previous example script will generate an error if the filename taken from the user does not exist in the current location. This problem has solved in this example. The os module is used here to check the existence of the filename that will be taken from the user. The check_closed() function has defined to check the file is closed or not that will be called if the file exists.

# Nhập mô -đun HĐH Để kiểm tra sự tồn tại của tệp Nhập HĐH# DRFINE Chức năng Kiểm tra tệp được đóng hoặc không def Check_closes (): & nbsp; & nbsp; Nếu fileHandler.closed == false: & nbsp; & nbsp; & nbsp; & nbsp; # In tin nhắn thành công & nbsp; & nbsp; & nbsp; & nbsp; in ("Tệp đã mở để đọc.") & nbsp; & nbsp; khác: & nbsp; & nbsp; & nbsp; & nbsp; # In thông báo lỗi & nbsp; & nbsp; & nbsp; & nbsp; in ("Tệp đã đóng.")
import os
# Drfine function check the file is closed or not
def check_closed():
    if fileHandler.closed == False:
        # Print the success message
        print("File has opened for reading.")
    else:
        # Print the error message
        print("File has closed.")

# Lấy tên tệp để kiểm tra tên tệp = đầu vào ("Nhập bất kỳ tên tệp hiện có nào: \ n")# Kiểm tra tệp tồn tại hoặc notif os.path.exists (tên tệp): & nbsp; & nbsp; # Mở tệp để đọc & nbsp; & nbsp; fileHandler = open (tên tệp, "r") & nbsp; & nbsp; # Gọi chức năng & nbsp; & nbsp; Check_Closes () khác: & nbsp; & nbsp; # In tin nhắn nếu tệp không tồn tại & nbsp; & nbsp; in ("Tệp không tồn tại.")
filename = input("Enter any existing filename:\n")
# Check the file exist or not
if os.path.exists(filename):
    # Open the file for reading
    fileHandler = open(filename, "r")
    # Call the function
    check_closed()
else:
    # Print message if the file does not exist
    print("File does not exist.")

Output:

Đầu ra sau sẽ xuất hiện sau khi thực thi tập lệnh trên. Ở đây, client.txt tồn tại ở vị trí hiện tại và thông báo thành công, File File đã mở để đọc, đã được in vì giá trị của tài sản đóng đã trả về sai.clients.txt exists in the current location, and the success message, “File has opened for reading,” has printed because the value of the closed property returned False.

Hướng dẫn python check if file is open by another process windows - python kiểm tra xem tệp có được mở bởi một cửa sổ quy trình khác không

Ví dụ-3: Kiểm tra tệp được mở hoặc không bằng cách sử dụng Oserror

Oserror tạo ra khi hàm đổi tên () được gọi nhiều hơn một lần cho một tệp đã được mở. Tạo một tệp Python với tập lệnh sau để kiểm tra tệp được mở hoặc đóng bằng cách sử dụng Oserror. Mô -đun HĐH đã được sử dụng trong tập lệnh để kiểm tra sự tồn tại của tệp và đổi tên tệp. Khi hàm đổi tên () được gọi lần thứ hai, Oserror sẽ được tạo và thông báo lỗi tùy chỉnh sẽ được in.OSError generates when the rename() function is called more than one time for a file that is opened already. Create a python file with the following script to check a file is opened or closed by using OSError. The os module has been used in the script to check the file’s existence and rename the file. When the rename() function is called for the second time, OSError will be generated, and the custom error message will be printed.

# Nhập mô -đun HĐH để kiểm tra sự tồn tại của tệp Nhập HĐH# Đặt tên tệp hiện có fileName = 'client.txt'# Đặt tên tệp mới mới Tên tệp): & nbsp; & nbsp; thử: & nbsp; & nbsp; & nbsp; & nbsp; # Gọi hàm đổi tên cho lần đầu tiên & nbsp; & nbsp; & nbsp; & nbsp; OS.RENAME (tên tệp, tên mới) & nbsp; & nbsp; & nbsp; & nbsp; # Gọi hàm đổi tên cho lần thứ hai & nbsp; & nbsp; & nbsp; & nbsp; OS.RENAME (tên tệp, tên mới) & nbsp; & nbsp; # Lỗi nếu tệp đã mở & nbsp; & nbsp; ngoại trừ Oserror: & nbsp; & nbsp; & nbsp; & nbsp; in ("Tệp vẫn được mở.")
import os
# Set the existing filename
filename = 'clients.txt'
# Set the new filename
newname = 'customers.txt'
# Check the file exist or not
if os.path.exists(filename):
    try:
        # Call the rename function for the first time
        os.rename(filename, newname)
        # Call the rename function for the second time
        os.rename(filename, newname)
    # Raise error if the file has opened
    except OSError:
        print("File is still opened.")

khác: & nbsp; & nbsp; # In tin nhắn nếu tệp không tồn tại & nbsp; & nbsp; in ("Tệp không tồn tại.")
    # Print message if the file does not exist
    print("File does not exist.")

Output:

Đầu ra sau sẽ xuất hiện sau khi thực thi tập lệnh trên. Ở đây, client.txt tồn tại ở vị trí hiện tại và thông báo lỗi, tệp vẫn được mở, đã được in vì ngoại lệ oserror đã tạo khi hàm đổi tên thứ hai () đã được thực thi.clients.txt exists in the current location, and the error message, “File is still opened,” has printed because the OSError exception has generated when the second rename() function has been executed.

Hướng dẫn python check if file is open by another process windows - python kiểm tra xem tệp có được mở bởi một cửa sổ quy trình khác không

Conclusion:

Khi chúng ta cần làm việc với cùng một tệp nhiều lần trong một tập lệnh, điều cần thiết là phải biết liệu tệp được mở hay đóng. Tốt hơn là gọi hàm đóng () để đóng tệp sau khi hoàn thành thao tác tệp. Lỗi xảy ra khi một tệp được mở lần thứ hai trong cùng một tập lệnh mà không đóng nó. Các giải pháp khác nhau cho vấn đề này đã được thể hiện trong hướng dẫn này bằng cách sử dụng các ví dụ đơn giản để giúp người dùng Python.

Thông tin về các Tác giả

Hướng dẫn python check if file is open by another process windows - python kiểm tra xem tệp có được mở bởi một cửa sổ quy trình khác không

Tôi là một huấn luyện viên của các khóa học lập trình web.Tôi thích viết bài báo hoặc hướng dẫn về các chủ đề CNTT khác nhau.Tôi có một kênh YouTube trong đó nhiều loại hướng dẫn dựa trên Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel, v.v.