### Detect Current Shell Source: https://github.com/sarugaku/shellingham/blob/master/README.rst Use this function to get the name and command of the current shell. It returns a 2-tuple: the shell name (lowercased) and the command used to run it. Raises `ShellDetectionFailure` if detection fails. ```python >>> import shellingham >>> shellingham.detect_shell() ('bash', '/bin/bash') ``` -------------------------------- ### Python CLI App with Shell Awareness Source: https://context7.com/sarugaku/shellingham/llms.txt Integrates Shellingham to detect the current shell, generate completion scripts, and launch subshells. Includes fallback logic for shell detection failures. ```python import shellingham import os import subprocess import sys class ShellAwareApp: """Example CLI application with shell-aware features.""" COMPLETION_SCRIPTS = { 'bash': ''' _myapp_completion() { COMPREPLY=($(myapp --complete "${COMP_WORDS[@]:1}")) } complete -F _myapp_completion myapp ''', 'zsh': ''' #compdef myapp _myapp() { compadd $(myapp --complete ${words[@]:1}) } _myapp "$@" ''', 'fish': ''' complete -c myapp -a "(myapp --complete (commandline -cop))" ''', } def __init__(self): self.shell_name = None self.shell_path = None self._detect_shell() def _detect_shell(self): """Detect the current shell with fallback.""" try: self.shell_name, self.shell_path = shellingham.detect_shell() except shellingham.ShellDetectionFailure: if os.name == 'posix': self.shell_path = os.environ.get('SHELL', '/bin/sh') self.shell_name = os.path.basename(self.shell_path).lower() elif os.name == 'nt': self.shell_path = os.environ.get('COMSPEC', 'cmd.exe') self.shell_name = 'cmd' def generate_completion(self): """Generate shell completion script for the detected shell.""" if self.shell_name in self.COMPLETION_SCRIPTS: return self.COMPLETION_SCRIPTS[self.shell_name] return f"# No completion support for {self.shell_name}" def launch_subshell(self, env_vars=None): """Launch a subshell with optional environment variables.""" env = os.environ.copy() if env_vars: env.update(env_vars) print(f"Launching {self.shell_name} subshell...") subprocess.run([self.shell_path], env=env) def get_shell_info(self): """Return shell information as a dictionary.""" return { 'name': self.shell_name, 'path': self.shell_path, 'supports_completion': self.shell_name in self.COMPLETION_SCRIPTS, } # Usage app = ShellAwareApp() info = app.get_shell_info() print(f"Current shell: {info['name']}") print(f"Shell path: {info['path']}") print(f"Completion support: {info['supports_completion']}") # Generate completion script print("\nCompletion script:") print(app.generate_completion()) ``` -------------------------------- ### Detect Shell Environment with Python Source: https://context7.com/sarugaku/shellingham/llms.txt Use detect_shell to identify the current shell or a specific process. Includes a fallback mechanism for when detection fails. ```python import shellingham # Basic usage - detect the current shell shell_name, shell_path = shellingham.detect_shell() print(f"Running in: {shell_name}") print(f"Shell path: {shell_path}") # Output example: # Running in: bash # Shell path: /bin/bash # Detect shell for a specific process ID shell_name, shell_path = shellingham.detect_shell(pid=1234) # Limit the process tree traversal depth (default is 10) shell_name, shell_path = shellingham.detect_shell(max_depth=5) # Handling detection failure with proper fallback import os def get_shell_with_fallback(): try: return shellingham.detect_shell() except shellingham.ShellDetectionFailure: # Provide a sensible default based on OS if os.name == 'posix': shell = os.environ.get('SHELL', '/bin/sh') return (os.path.basename(shell).lower(), shell) elif os.name == 'nt': shell = os.environ.get('COMSPEC', 'cmd.exe') return (os.path.basename(shell).lower().replace('.exe', ''), shell) raise shell_name, shell_path = get_shell_with_fallback() print(f"Shell: {shell_name} at {shell_path}") ``` -------------------------------- ### detect_shell() - Detect the surrounding shell Source: https://context7.com/sarugaku/shellingham/llms.txt The main entry point for detecting the surrounding shell. This function traverses the process tree to find the first parent process that is a known shell. It returns a tuple containing the shell name and its command path. ```APIDOC ## detect_shell() ### Description Detects the surrounding shell by traversing the process tree upwards from the current process or a specified PID. Returns the shell name and its command path. ### Method Python Function Call ### Parameters - **pid** (int) - Optional - The process ID to start traversal from. Defaults to the current process. - **max_depth** (int) - Optional - The maximum depth to traverse the process tree. Defaults to 10. ### Request Example ```python import shellingham # Basic usage shell_name, shell_path = shellingham.detect_shell() print(f"Running in: {shell_name}") print(f"Shell path: {shell_path}") # With specific PID and max_depth shell_name, shell_path = shellingham.detect_shell(pid=1234, max_depth=5) # Handling detection failure try: shell_name, shell_path = shellingham.detect_shell() except shellingham.ShellDetectionFailure: # Provide fallback logic pass ``` ### Response #### Success Response (tuple) - **shell_name** (str) - The name of the detected shell (lowercased). - **shell_path** (str) - The full command path to the shell executable. #### Response Example ```json { "shell_name": "bash", "shell_path": "/bin/bash" } ``` #### Error Response - **ShellDetectionFailure** - Raised when no shell can be found within the specified depth or if process information is unavailable. ``` -------------------------------- ### shellingham.detect_shell() Source: https://github.com/sarugaku/shellingham/blob/master/README.rst Detects the surrounding shell environment of the current process. ```APIDOC ## detect_shell() ### Description Detects what shell the current Python executable is running in by inspecting the process environment. ### Returns - **tuple** - A 2-tuple containing (shell_name, command_path). The shell name is always lowercased. ### Exceptions - **ShellDetectionFailure** - Raised if the surrounding shell cannot be detected. ### Example ```python import shellingham try: shell = shellingham.detect_shell() print(f"Shell: {shell[0]}, Path: {shell[1]}") except shellingham.ShellDetectionFailure: # Handle failure case pass ``` ``` -------------------------------- ### Handle Shell Detection Failure Source: https://github.com/sarugaku/shellingham/blob/master/README.rst Wrap `detect_shell` in a try-except block to gracefully handle cases where the shell cannot be detected. Provide a default shell or action in the `except` block. ```python try: shell = shellingham.detect_shell() except shellingham.ShellDetectionFailure: shell = provide_default() ``` -------------------------------- ### Provide Default Shell Based on OS Source: https://github.com/sarugaku/shellingham/blob/master/README.rst A function to determine a default shell based on the operating system. It checks for POSIX systems (using the SHELL environment variable) and Windows systems (using COMSPEC). Raises `NotImplementedError` for unsupported OS. ```python import os def provide_default(): if os.name == 'posix': return os.environ['SHELL'] elif os.name == 'nt': return os.environ['COMSPEC'] raise NotImplementedError(f'OS {os.name!r} support not available') ``` -------------------------------- ### Handle ShellDetectionFailure Exception Source: https://context7.com/sarugaku/shellingham/llms.txt Catch ShellDetectionFailure to implement graceful fallbacks when the shell cannot be identified. This is essential for robust application configuration. ```python import shellingham import os import sys def configure_shell_completion(): """Configure shell completion with graceful fallback.""" try: shell_name, shell_path = shellingham.detect_shell() except shellingham.ShellDetectionFailure as e: print(f"Shell detection failed: {e}", file=sys.stderr) # Fall back to SHELL environment variable on POSIX if os.name == 'posix' and 'SHELL' in os.environ: shell_path = os.environ['SHELL'] shell_name = os.path.basename(shell_path).lower() # Fall back to COMSPEC on Windows elif os.name == 'nt' and 'COMSPEC' in os.environ: shell_path = os.environ['COMSPEC'] shell_name = os.path.basename(shell_path).lower().rstrip('.exe') else: print("Could not determine shell, skipping completion setup") return None # Configure completion based on detected shell completions = { 'bash': 'source ~/.my_app_completion.bash', 'zsh': 'source ~/.my_app_completion.zsh', 'fish': 'source ~/.my_app_completion.fish', 'powershell': '. ~/.my_app_completion.ps1', 'pwsh': '. ~/.my_app_completion.ps1', } if shell_name in completions: print(f"To enable completion, add to your shell config:") print(f" {completions[shell_name]}") return shell_name, shell_path # Usage result = configure_shell_completion() if result: print(f"Detected shell: {result[0]}") ``` -------------------------------- ### SHELL_NAMES Constant Source: https://context7.com/sarugaku/shellingham/llms.txt A constant set containing all recognized shell names that Shellingham can detect. Useful for validation or checking if a process is a known shell. ```APIDOC ## SHELL_NAMES ### Description A constant set (`set`) containing the string names of all shell types that Shellingham recognizes and can detect. This set is useful for validating if a given process name corresponds to a known shell. ### Usage Import `SHELL_NAMES` from `shellingham._core` to access the set. It can be used for checking, filtering, or displaying supported shells. ### Example ```python from shellingham._core import SHELL_NAMES # Check if a process name is a known shell def is_known_shell(process_name): name = process_name.lower() # Normalize Windows executable names if name.endswith('.exe'): name = name[:-4] return name in SHELL_NAMES print(f"Is 'bash' a known shell? {is_known_shell('bash')}") print(f"Is 'python' a known shell? {is_known_shell('python')}") print(f"Is 'pwsh.exe' a known shell? {is_known_shell('pwsh.exe')}") # Display all supported shells print("\nSupported shells:") for shell in sorted(SHELL_NAMES): print(f" - {shell}") ``` ### Response Example (Output of printing sorted SHELL_NAMES) ``` Supported shells: - ash - bash - cmd - csh - dash - elvish - fish - ksh - nu - powershell - pwsh - sh - tcsh - xonsh - zsh ``` ``` -------------------------------- ### Validate Shell Names with SHELL_NAMES Source: https://context7.com/sarugaku/shellingham/llms.txt Access the SHELL_NAMES constant to list supported shells or validate process names. Note that Windows executable extensions are stripped during validation. ```python from shellingham._core import SHELL_NAMES # View all supported shells print("Supported shells:") for shell in sorted(SHELL_NAMES): print(f" - {shell}") # Output: # - ash # - bash # - cmd # - csh # - dash # - elvish # - fish # - ksh # - nu # - powershell # - pwsh # - sh # - tcsh # - xonsh # - zsh # Check if a process is a known shell def is_known_shell(process_name): """Check if a process name is a recognized shell.""" name = process_name.lower() # Handle Windows executables if name.endswith('.exe'): name = name[:-4] return name in SHELL_NAMES print(is_known_shell('bash')) # True print(is_known_shell('python')) # False print(is_known_shell('pwsh.exe')) # True print(is_known_shell('fish')) # True ``` -------------------------------- ### ShellDetectionFailure Exception Source: https://context7.com/sarugaku/shellingham/llms.txt An exception class raised when shell detection fails. This occurs when no shell can be found in the process tree within the specified depth, or when the system doesn't provide the necessary process information. ```APIDOC ## ShellDetectionFailure ### Description An exception raised by `shellingham.detect_shell()` when it cannot successfully identify a shell in the process tree. This typically happens if the traversal depth is exhausted before finding a shell, or if the underlying system calls to get process information fail. ### Usage Catch this exception to provide fallback mechanisms or inform the user about the detection failure. ### Example ```python import shellingham import os import sys try: shell_name, shell_path = shellingham.detect_shell() except shellingham.ShellDetectionFailure as e: print(f"Shell detection failed: {e}", file=sys.stderr) # Fallback logic based on OS and environment variables if os.name == 'posix' and 'SHELL' in os.environ: shell_path = os.environ['SHELL'] shell_name = os.path.basename(shell_path).lower() elif os.name == 'nt' and 'COMSPEC' in os.environ: shell_path = os.environ['COMSPEC'] shell_name = os.path.basename(shell_path).lower().rstrip('.exe') else: print("Could not determine shell, using default.") shell_name = 'unknown' shell_path = 'unknown' print(f"Using fallback shell: {shell_name} at {shell_path}") ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.