Python bindings for FUSE (Filesystem in USErspace) enabling custom userspace filesystems
—
Integrated command line argument processing and FUSE option management for filesystem mounting, configuration, and runtime behavior control.
The primary class for implementing FUSE filesystems with integrated command line processing.
class Fuse:
"""
Main FUSE filesystem class.
Base class for implementing filesystems with built-in command line
argument processing and FUSE integration.
"""
fuse_args: FuseArgs # Command line arguments
parser: FuseOptParse # Option parser
multithreaded: bool # Enable multithreading
def __init__(self, *args, **kwargs):
"""
Initialize FUSE filesystem.
Args:
version (str, optional): Version string for --version output
usage (str, optional): Usage string for help output
dash_s_do (str, optional): Single-threading behavior
parser_class (class, optional): Custom parser class
fuse_args (FuseArgs, optional): Pre-configured arguments
**kwargs: Additional initialization parameters
"""
def parse(self, *args, **kwargs):
"""
Parse command line arguments.
Args:
*args: Arguments to parse (default: sys.argv)
errex (int): Exit code on error (default: don't exit)
values (object): Object to store parsed values
Returns:
Parsed arguments and options
"""
def main(self):
"""
Enter filesystem service loop.
This method starts the FUSE main loop and handles filesystem
operations until unmount or termination.
Returns:
int: Exit status (normally doesn't return)
"""
@classmethod
def fuseoptref(cls):
"""
Get FUSE library supported options reference.
Returns:
FuseArgs: Reference args containing all supported FUSE options
"""Usage Example:
class MyFS(Fuse):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.multithreaded = False # Single-threaded filesystem
def getattr(self, path):
# ... implement filesystem methods
pass
# Create and run filesystem
fs = MyFS(
version="MyFS 1.0",
usage="MyFS filesystem\n\n" + Fuse.fusage
)
fs.parse(errex=1) # Exit on parse errors
fs.main() # Start filesystem loopStructure for managing FUSE command line arguments and mount options.
class FuseArgs(SubOptsHive):
"""
FUSE command line arguments container.
Manages FUSE-specific command line options and mount arguments.
"""
mountpoint: str # Mount point path
modifiers: dict # Boolean option modifiers
fuse_modifiers: dict # FUSE option mappings
def getmod(self, opt):
"""
Get modifier value.
Args:
opt (str): Modifier name
Returns:
bool: Modifier value
"""
def setmod(self, opt):
"""
Set modifier to True.
Args:
opt (str): Modifier name
"""
def unsetmod(self, opt):
"""
Set modifier to False.
Args:
opt (str): Modifier name
"""
def assemble(self):
"""
Assemble arguments for FUSE.
Returns:
list: Arguments suitable for FUSE main()
"""
def filter(self, other=None):
"""
Filter arguments against option reference.
Args:
other (FuseArgs, optional): Reference args to filter against.
If None, uses fuseoptref() result.
"""Usage Example:
def custom_parse(self):
# Access parsed arguments
args = self.fuse_args
# Check for specific modifiers
if args.getmod('foreground'):
print("Running in foreground mode")
if args.getmod('showhelp'):
self.parser.print_help()
sys.exit(0)
# Get mount point
if args.mountpoint:
print(f"Mounting at: {args.mountpoint}")
else:
print("No mount point specified")
sys.exit(1)Enhanced option parser with FUSE-specific extensions and sub-option support.
class FuseOptParse(SubbedOptParse):
"""
FUSE option parser.
Enhanced OptionParser with FUSE integration and sub-option support.
"""
fuse_args: FuseArgs # Associated FuseArgs instance
def parse_args(self, args=None, values=None):
"""
Parse command line arguments.
Args:
args (list): Arguments to parse
values (object): Object to store values
Returns:
tuple: (options, args) tuple
"""
def add_option(self, *args, **kwargs):
"""
Add command line option.
Args:
*args: Option names (-f, --foreground)
**kwargs: Option configuration
Returns:
Option: Created option object
"""
def print_help(self, file=None):
"""
Print help message including FUSE options.
Args:
file: Output file (default: sys.stdout)
"""
def print_version(self, file=None):
"""
Print version information.
Args:
file: Output file (default: sys.stdout)
"""Usage Example:
class MyFS(Fuse):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Add custom options
self.parser.add_option(
'-d', '--debug',
action='store_true',
help='Enable debug mode'
)
self.parser.add_option(
'--cache-size',
type='int',
default=1024,
help='Cache size in MB'
)
def parse(self, *args, **kwargs):
options, args = super().parse(*args, **kwargs)
# Access custom options
if hasattr(options, 'debug') and options.debug:
self.enable_debug()
if hasattr(options, 'cache_size'):
self.set_cache_size(options.cache_size)
return options, argsSpecialized help formatter for FUSE option output.
class FuseFormatter(SubbedOptIndentedFormatter):
"""
FUSE help formatter.
Formats help output for FUSE-specific options and sub-options.
"""Control FUSE Python API version for compatibility.
fuse_python_api: tuple # Global API version (0, 2)
def get_fuse_python_api():
"""
Get current FUSE Python API version.
Returns:
tuple: API version tuple (major, minor)
"""
def get_compat_0_1():
"""
Check if using legacy 0.1 API compatibility.
Returns:
bool: True if using 0.1 compatibility mode
"""Usage Example:
# Set API version before importing/using FUSE
import fuse
fuse.fuse_python_api = (0, 2)
# Or set via environment variable
# export FUSE_PYTHON_API=0.2
class MyFS(Fuse):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Check API version
if fuse.get_compat_0_1():
print("Warning: Using legacy 0.1 API")
else:
print(f"Using API version: {fuse.get_fuse_python_api()}")Common FUSE mount options that can be set via command line:
-f, --foreground: Run in foreground (don't daemonize)-d, --debug: Enable debug output-s: Single-threaded operation-o opt[,opt...]: Mount options-o parameter)allow_other: Allow access by other usersallow_root: Allow access by rootdefault_permissions: Enable permission checkingro: Read-only filesystemrw: Read-write filesystemsuid: Allow suid/sgid bitsnosuid: Disallow suid/sgid bitsdev: Allow device filesnodev: Disallow device filesexec: Allow program executionnoexec: Disallow program executionUsage Example:
# Command line usage:
# python myfs.py /mnt/point -f -o allow_other,default_permissions
class MyFS(Fuse):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Add filesystem-specific options
self.parser.add_option(
'-o',
dest='mount_options',
help='Mount options'
)
def parse(self, *args, **kwargs):
options, args = super().parse(*args, **kwargs)
# Process mount options
if hasattr(options, 'mount_options'):
opts = options.mount_options.split(',')
for opt in opts:
if opt == 'ro':
self.read_only = True
elif opt == 'allow_other':
self.allow_other = TrueCommand line parsing can encounter various errors:
Usage Example:
def main():
fs = MyFS(version="MyFS 1.0")
try:
fs.parse(errex=1) # Exit on parse errors
fs.main()
except OptParseError as e:
print(f"Command line error: {e}")
sys.exit(1)
except Exception as e:
print(f"Filesystem error: {e}")
sys.exit(1)errex=1 in parse() to exit on command line errorsInstall with Tessl CLI
npx tessl i tessl/pypi-fuse-python