Python os.fchown() 方法



描述

Python os.fchown() 方法用於更改給定檔案的擁有者和組 ID。只有超級使用者才有許可權使用此方法修改或執行檔案操作。因此,執行程式碼時請使用“sudo”命令。

fchown() 方法接受三個引數,即 fd、uid 和 gid。“uid”和“gid”將擁有者和組 ID 設定為“fd”引數指定的 檔案。如果我們想保留任何 ID 不變,則將其設定為 -1。

注意 - 此方法自 Python 2.6 起可用。並且,只能在 UNIX 平臺上使用。

語法

以下是 Python os.fchown() 方法的語法:

os.fchown(fd, uid, gid);

引數

Python os.fchown() 方法接受以下引數:

  • fd - 這是需要設定擁有者 ID 和組 ID 的檔案描述符。

  • uid - 這是要為檔案設定的擁有者 ID。

  • gid - 這是要為檔案設定的組 ID。

返回值

Python os.fchown() 方法不返回任何值。

示例

以下示例顯示了 fchown() 方法的用法。在這裡,我們以只讀模式開啟一個檔案,然後嘗試使用 fchown() 設定檔案的擁有者和組 ID。

import os, sys, stat
# Now open a file "/tmp/foo.txt"
fd = os.open( "/tmp", os.O_RDONLY )
# Set the user Id to 100 for this file.
os.fchown( fd, 100, -1)
# Set the group Id to 50 for this file.
os.fchown( fd, -1, 50)
print("Changed ownership successfully!!")
# Close opened file.
os.close( fd )

執行上述程式時,會產生以下結果:

Changed ownership successfully!!

示例

如前所述,只有超級使用者才能修改給定檔案的擁有權。在下面的示例中,我們嘗試修改擁有者 ID,這將導致 PermissionError。

import os
# Open a file
fileObj = os.open("newFile.txt", os.O_RDONLY)
try:
   os.fchown(fileObj, 10,-1)
   print("Ownership changed for the given file.")
except PermissionError:
   print("Don't have permission to change the owner/group id of this file.")
except OSError as e:
   print(f"Error: {e.strerror}")
# Close the file
os.close(fileObj)

執行上述程式後,會產生以下結果:

Don't have permission to change the owner/group id of this file.
python_files_io.htm
廣告