oschmod: Cross-platform file permissions
oschmod is a Python library that provides a Windows and Linux compatible `chmod` function for managing file permissions. It aims to offer a consistent API for setting POSIX-like permissions across various operating systems, including Windows, which natively uses Access Control Lists (ACLs) rather than POSIX mode bits. The current version is 0.3.12, and it maintains a moderate release cadence primarily for bug fixes and compatibility updates.
Common errors
-
FileNotFoundError: [Errno 2] No such file or directory: 'non_existent_file.txt'
cause The path provided to `oschmod` does not point to an existing file or directory.fixVerify that the `file_path` argument is correct and that the file or directory exists at that location before calling `oschmod`. -
PermissionError: [Errno 13] Permission denied: 'some_protected_file.txt'
cause The Python process does not have sufficient privileges to modify the permissions of the specified file or directory.fixRun your Python script with elevated permissions (e.g., as an administrator on Windows, or using `sudo` on Linux/macOS), or ensure the current user has ownership/write permissions to the target path. -
AttributeError: module 'oschmod' has no attribute 'chmod'
cause You are trying to call `oschmod.chmod()` but the main function within the `oschmod` module for changing permissions is also named `oschmod`.fixCall `oschmod.oschmod(path, mode)` instead of `oschmod.chmod(path, mode)`. If you used `import oschmod`, it would be `oschmod.oschmod(...)`.
Warnings
- gotcha On Windows, `oschmod` translates POSIX-like mode bits to Windows Access Control Lists (ACLs). This is an approximation and not all POSIX modes have direct ACL equivalents, which can lead to slightly different effective permissions or limitations compared to a true POSIX system.
- gotcha The `oschmod` function is not recursive by default. It only modifies the permissions of the specified file or directory itself. To apply permissions to the contents of a directory, you must manually traverse the directory tree (e.g., using `os.walk`).
- gotcha Attempting to change permissions on files or directories where the current user lacks the necessary administrative or ownership privileges will result in a `PermissionError`. This is especially common on Windows for system files or on Linux for files owned by root.
Install
-
pip install oschmod
Imports
- oschmod
import oschmod; oschmod.chmod('file', 0o755)from oschmod import oschmod
Quickstart
import os
from oschmod import oschmod
# Create a dummy file for demonstration
file_path = 'my_test_file.txt'
with open(file_path, 'w') as f:
f.write('Hello, oschmod!')
print(f"Initial permissions for {file_path}: {oct(os.stat(file_path).st_mode & 0o777)}")
# Set permissions to rwxr-xr-x (0o755)
oschmod(file_path, 0o755)
print(f"New permissions for {file_path}: {oct(os.stat(file_path).st_mode & 0o777)}")
# Clean up the dummy file
os.remove(file_path)