### Launch the pyshortcut GUI Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Open the graphical interface for building shortcuts, requiring wxPython to be installed. ```default ~> pyshortcut --wxgui ``` -------------------------------- ### Install pyshortcuts with GUI support Source: https://github.com/newville/pyshortcuts/blob/master/doc/install.md To enable the graphical user interface for pyshortcuts, install the package with the 'gui' extra. This will also install the wxPython package. ```bash pip install "pyshortcuts[gui]" ``` -------------------------------- ### Install pyshortcuts Source: https://github.com/newville/pyshortcuts/blob/master/doc/install.md Use this command to install the base pyshortcuts package. Dependencies like charset-normalizer and pywin32 (on Windows) will be installed automatically if needed. ```bash pip install pyshortcuts ``` -------------------------------- ### make_shortcut(script, ...) Source: https://github.com/newville/pyshortcuts/blob/master/doc/python.md Creates a desktop or start menu shortcut for a given script or command. ```APIDOC ## make_shortcut ### Description Creates a desktop shortcut for a specified script or command. ### Parameters - **script** (string) - Required - Path to script, may include command-line arguments. - **name** (string) - Optional - Name to display for shortcut. - **description** (string) - Optional - Longer description of script. - **icon** (string) - Optional - Filename for icon file. - **working_dir** (string) - Optional - Directory where to run the script in. - **folder** (string) - Optional - Name of subfolder of Desktop for shortcut. - **terminal** (bool) - Optional - Whether to run in a Terminal. - **desktop** (bool) - Optional - Whether to add shortcut to Desktop. - **startmenu** (bool) - Optional - Whether to add shortcut to Start Menu. - **executable** (string) - Optional - Name of executable to use. - **noexe** (bool) - Optional - Whether to use no executable, so that the script is entire command. ### Request Example from pyshortcuts import make_shortcut make_shortcut('/home/user/bin/myapp.py', name='MyApp', icon='/home/user/icons/myicon.ico') ``` -------------------------------- ### Get User Folders Source: https://context7.com/newville/pyshortcuts/llms.txt Retrieves platform-specific user folder paths including home, desktop, and Start Menu. Useful for determining shortcut creation locations. ```python from pyshortcuts import get_folders # Get user-specific folders folders = get_folders() print(f"Home directory: {folders.home}") print(f"Desktop: {folders.desktop}") print(f"Start Menu: {folders.startmenu}") ``` -------------------------------- ### CLI: pyshortcut command Source: https://github.com/newville/pyshortcuts/blob/master/README.md The pyshortcut command-line program allows users to create desktop and start menu shortcuts for Python scripts. ```APIDOC ## CLI: pyshortcut ### Description Creates a shortcut for a specified Python script or command. ### Parameters #### Positional Arguments - **scriptname** (string) - Required - The path to the script or the command to be executed. #### Optional Arguments - **-n, --name** (string) - Optional - Name for the shortcut. - **-i, --icon** (string) - Optional - Path to the icon file. - **-f, --folder** (string) - Optional - Subfolder on desktop to place the icon. - **-e, --executable** (string) - Optional - Name of the executable to use. - **-t, --terminal** (boolean) - Optional - Run script in a Terminal Window (Default: True). - **-g, --gui** (boolean) - Optional - Run script as a GUI, with no Terminal Window (Default: False). - **-d, --desktop** (boolean) - Optional - Create desktop shortcut (Default: True). - **-s, --startmenu** (boolean) - Optional - Create Start Menu shortcut (Default: True). - **-w, --wxgui** (boolean) - Optional - Run GUI version of pyshortcut. - **-b, --bootstrap** (boolean) - Optional - Create a desktop shortcut to run GUI version of pyshortcut. ``` -------------------------------- ### get_folders Source: https://context7.com/newville/pyshortcuts/llms.txt Retrieves platform-specific user folder paths including home, desktop, and Start Menu locations. ```APIDOC ## get_folders ### Description Returns platform-specific user folder paths as a named tuple containing the home directory, desktop location, and Start Menu folder. ### Response - **home** (string) - Path to the user's home directory - **desktop** (string) - Path to the user's desktop folder - **startmenu** (string) - Path to the user's Start Menu folder ``` -------------------------------- ### Create shortcuts programmatically with make_shortcut Source: https://context7.com/newville/pyshortcuts/llms.txt Use the make_shortcut function to generate desktop or Start Menu entries. The function returns a namedtuple containing details about the created shortcut. ```python from pyshortcuts import make_shortcut # Basic shortcut for a Python script scut = make_shortcut( '/home/user/scripts/myapp.py', name='My Application', icon='/home/user/icons/myicon.ico' ) # Shortcut with all options scut = make_shortcut( script='/path/to/script.py --option value', # Script with arguments name='Data Processor', # Display name description='Processes daily data files', # Tooltip description icon='/path/to/icon.ico', # Custom icon working_dir='/path/to/workdir', # Working directory folder='MyTools', # Subfolder on Desktop terminal=True, # Run in terminal window desktop=True, # Create desktop shortcut startmenu=True, # Create Start Menu entry executable='/usr/bin/python3' # Specific Python executable ) # Shortcut to run a pip command (using _ for current Python) make_shortcut( '_ -m pip install --upgrade mypackage', name='Update MyPackage' ) # GUI application shortcut (no terminal window) make_shortcut( '/path/to/gui_app.py', name='My GUI App', terminal=False ) # Returns a Shortcut namedtuple with fields: # name, description, icon, target, working_dir, script, # full_script, arguments, desktop_dir, startmenu_dir print(f"Shortcut created: {scut.target}") print(f"Desktop location: {scut.desktop_dir}") ``` -------------------------------- ### Get current time in ISO format Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md Provides a shorthand for datetime.isoformat with customizable timespec and separator. ```python from datetime import datetime def isotime(dtime=None, timespec='seconds', sep=' '): """return ISO format of current timestamp: 2024-04-27 17:31:12 """ if dtime is None: dtime = datetime.now() return datetime.isoformat(dtime, timespec=timespec, sep=sep) ``` -------------------------------- ### Create GUI Shortcut with PyShortcuts Source: https://context7.com/newville/pyshortcuts/llms.txt Use this script to create a desktop shortcut for the PyShortcuts GUI. It determines the correct script directory based on the operating system and creates a shortcut that launches the GUI without a terminal window. Ensure PyShortcuts is installed in your environment. ```python #!/usr/bin/env python """Create a desktop shortcut for the PyShortcuts GUI""" import sys from pathlib import Path from pyshortcuts import make_shortcut, uname # Determine the correct bin directory bindir = 'Scripts' if uname.startswith('win') else 'bin' # Build path to pyshortcut command script = Path(sys.prefix, bindir, 'pyshortcut').resolve().as_posix() # Create GUI shortcut (no terminal window) scut = make_shortcut( f"{script} --wxgui", name='PyShortcuts', terminal=False ) print(f"Created GUI shortcut: {scut.target}") # Alternative: use the built-in bootstrap command # From command line: pyshortcut --bootstrap ``` -------------------------------- ### Get current working directory path Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md Returns the absolute path of the current working directory. ```python pathlib.Path('.').resolve().as_posix() ``` -------------------------------- ### Get home directory path Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md Retrieves the user's home directory path, with special handling for SUDO_USER on POSIX and win32com on Windows. ```python pathlib.Path.home().resolve().as_posix() ``` -------------------------------- ### Get Current Working Directory Safely Source: https://context7.com/newville/pyshortcuts/llms.txt Returns the current working directory, falling back to the home directory if permission errors occur. Always returns a POSIX-style path. ```python from pyshortcuts import get_cwd # Get current working directory cwd = get_cwd() print(cwd) # Output: '/current/working/directory' ``` -------------------------------- ### Get User Home Directory Source: https://context7.com/newville/pyshortcuts/llms.txt Retrieves the user's home directory path, handling edge cases like sudo users and using the Windows COM API for reliability. Always returns a POSIX-style path. ```python from pyshortcuts import get_homedir # Get user home directory home = get_homedir() print(home) # Output: '/home/username' (Linux/macOS) or 'C:/Users/username' (Windows) ``` -------------------------------- ### Get Current Timestamp in ISO Format Source: https://context7.com/newville/pyshortcuts/llms.txt Returns the current timestamp in ISO format. Supports custom separators and time precision, and can format specific datetimes or Unix timestamps. ```python from pyshortcuts import isotime # Current timestamp with default format timestamp = isotime() print(timestamp) # Output: '2024-04-27 17:31:12' # Custom separator between date and time timestamp = isotime(sep='T') print(timestamp) # Output: '2024-04-27T17:31:12' # Different time precision timestamp = isotime(timespec='milliseconds') print(timestamp) # Output: '2024-04-27 17:31:12.456' # Format a specific datetime or timestamp from datetime import datetime dt = datetime(2024, 1, 15, 10, 30, 0) print(isotime(dt)) # Output: '2024-01-15 10:30:00' # From a Unix timestamp print(isotime(1704067800)) # Output: '2024-01-01 00:30:00' ``` -------------------------------- ### Bootstrap the pyshortcut GUI shortcut Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Create a desktop shortcut that launches the pyshortcut GUI application. ```default ~> pyshortcut --bootstrap ``` -------------------------------- ### Create a Shortcut from the Command Line Source: https://github.com/newville/pyshortcuts/blob/master/doc/python.md Create a shortcut directly from the command line using the pyshortcut utility. This is a convenient alternative for simple commands. ```bash ~> pyshortcut -n "Update Pyshortcuts" "_ -m pip install pyshortcuts" ``` -------------------------------- ### View pyshortcut command syntax Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Display the usage pattern and available arguments for the pyshortcut command. ```default pyshortcut [-h] [-v] [-n NAME] [-i ICON] [-f FOLDER] [-e EXE] [-t] [-g] [-d] [-s] [-w] [scriptname] ``` -------------------------------- ### Create Shortcut from Command Line Source: https://github.com/newville/pyshortcuts/blob/master/README.md Use the `pyshortcut` command-line program to create shortcuts. Specify the shortcut name, icon, and the script path. Arguments for the script can be included by enclosing the script path and arguments in double quotes. ```bash ~> pyshortcut -n MyApp -i /home/user/icons/myicon.icns /home/user/bin/myapp.py ``` ```bash ~> pyshortcut -n MyApp -i /home/user/icons/myicon.icns "/home/user/bin/myapp.py -t 10" ``` -------------------------------- ### Create Shortcut and Access Properties Source: https://context7.com/newville/pyshortcuts/llms.txt Creates a shortcut for a given script and returns a named tuple with all resolved shortcut information. Access properties like name, target, and directories. ```python from pyshortcuts import make_shortcut scut = make_shortcut('/path/to/myapp.py', name='MyApp') # Access shortcut properties print(f"Name: {scut.name}") # Display name: 'MyApp' print(f"Description: {scut.description}") # Description (defaults to name) print(f"Icon: {scut.icon}") # Full path to icon file print(f"Target: {scut.target}") # Shortcut filename: 'MyApp.lnk' print(f"Working dir: {scut.working_dir}") # Working directory print(f"Script: {scut.script}") # Script basename print(f"Full script: {scut.full_script}") # Full path to script print(f"Arguments: {scut.arguments}") # Command-line arguments print(f"Desktop dir: {scut.desktop_dir}") # Desktop folder path print(f"Start Menu: {scut.startmenu_dir}") # Start Menu folder path ``` -------------------------------- ### Create shortcuts via command-line interface Source: https://context7.com/newville/pyshortcuts/llms.txt The pyshortcut command-line tool allows for quick shortcut creation and GUI access directly from the terminal. ```bash # Basic usage - create shortcut for a Python script pyshortcut /home/user/bin/myapp.py # Specify shortcut name and custom icon pyshortcut -n "My App" -i /path/to/icon.ico /home/user/bin/myapp.py # Create shortcut with script arguments (use quotes) pyshortcut -n "Data Processor" "/home/user/scripts/process.py --input data.csv" # Create GUI shortcut (no terminal window) pyshortcut -g -n "My GUI" /home/user/apps/guiapp.py # Place shortcut in a Desktop subfolder pyshortcut -f "Python Tools" -n "MyTool" /path/to/tool.py # Use specific Python executable pyshortcut -e /usr/bin/python3.11 -n "Py311 Script" /path/to/script.py # Create shortcut for a pip command pyshortcut -n "Update Packages" "_ -m pip install --upgrade pip" # Desktop only (no Start Menu) pyshortcut -d -n "Desktop Only" /path/to/script.py # Launch the GUI for interactive shortcut creation pyshortcut --wxgui # Create a desktop shortcut to the GUI itself (bootstrap) pyshortcut --bootstrap # Show version pyshortcut --version # Command-line options: # -n, --name NAME Name for the shortcut # -i, --icon ICON Path to icon file (.ico, .icns, .png) # -f, --folder FOLDER Subfolder on desktop for shortcut # -e, --executable EXE Python executable to use # -t, --terminal Run in terminal window (default: True) # -g, --gui Run as GUI without terminal (default: False) # -d, --desktop Create desktop shortcut (default: True) # -s, --startmenu Create Start Menu shortcut (default: True) # -w, --wxgui Launch GUI application # -b, --bootstrap Create shortcut to launch GUI ``` -------------------------------- ### Create a shortcut with script arguments Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Include command-line arguments for the target script by enclosing the path and arguments in double quotes. ```default ~> pyshortcut -n MyApp -i /home/user/icons/myicon.icns "/home/user/bin/myapp.py -t 10" ``` -------------------------------- ### Create a basic shortcut via CLI Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Use the pyshortcut command to generate a shortcut for a specified Python script with an icon. ```default ~> pyshortcut -n MyApp -i /home/user/icons/myicon.icns /home/user/bin/myapp.py ``` -------------------------------- ### Utility Functions Overview Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md A collection of helper functions for time formatting, file system management, and performance monitoring. ```APIDOC ## Utility Functions ### isotime() - **Description**: Returns the current timestamp in ISO format. - **Parameters**: - dtime (datetime) - Optional - The datetime object to format. - timepec (str) - Optional - The time specification (default: 'seconds'). - sep (str) - Optional - The separator between date and time (default: ' '). ### get_homedir() - **Description**: Returns the user's home directory as a POSIX-style string, handling SUDO_USER on POSIX and win32com on Windows. ### get_cwd() - **Description**: Returns the current working directory as a POSIX-style string. ### fix_filename(filename) - **Description**: Sanitizes a string to create a valid filename for any OS by replacing invalid characters with '_'. ### new_filename(filename) - **Description**: Ensures a filename is unique in the current directory by incrementing numeric suffixes. ### read_textfile(filename) - **Description**: Reads a text file or file-like object into a string, handling unicode encodings and normalizing line endings to '\n'. ### gformat(value, length) - **Description**: Formats a floating point number to a specific string length with maximum possible precision. ### sleep(duration) - **Description**: A high-precision sleep function using perf_counter to avoid inaccuracies found in standard time.sleep(). ### debugtimer(name, precision) - **Description**: Creates a DebugTimer object to track and report execution time for sections of code. - **Methods**: - add(message): Marks a time point with a description. - get_report(): Returns a report of total and incremental run times. - show(): Prints the timing report. ``` -------------------------------- ### Create a Desktop Shortcut for a Python Script Source: https://github.com/newville/pyshortcuts/blob/master/doc/python.md Use make_shortcut to create a shortcut for a Python script. Specify the script path, name, and optionally an icon. ```python from pyshortcuts import make_shortcut make_shortcut('/home/user/bin/myapp.py', name='MyApp', icon='/home/user/icons/myicon.ico') ``` -------------------------------- ### Internal logic for bootstrapping the GUI Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md The underlying Python code used by the bootstrap command to create the GUI shortcut. ```python #!/usr/bin/env python import os import sys from pyshortcuts import make_shortcut, platform bindir = 'Scripts' if platform.startswith('win') else 'bin' pyshortcut = os.path.normpath(os.path.join(sys.prefix, bindir, 'pyshortcut')) scut = make_shortcut(f"{pyshortcut:s} --wxgui", name='PyShortcut', terminal=False) ``` -------------------------------- ### pyshortcut Command-Line Tool Source: https://context7.com/newville/pyshortcuts/llms.txt The `pyshortcut` command-line tool offers a convenient way to create shortcuts directly from the terminal, supporting all options available in the Python API. ```APIDOC ## pyshortcut Command-Line Tool ### Description The `pyshortcut` command-line program provides quick shortcut creation from the terminal. It supports all options available in the Python API and can also launch the GUI application for interactive shortcut creation. ### Usage ```bash pyshortcut [OPTIONS] SCRIPT ``` ### Options - **-n, --name NAME**: Name for the shortcut. - **-i, --icon ICON**: Path to icon file (.ico, .icns, .png). - **-f, --folder FOLDER**: Subfolder on desktop for shortcut. - **-e, --executable EXE**: Python executable to use. - **-t, --terminal**: Run in terminal window (default: True). - **-g, --gui**: Run as GUI without terminal (default: False). - **-d, --desktop**: Create desktop shortcut (default: True). - **-s, --startmenu**: Create Start Menu shortcut (default: True). - **-w, --wxgui**: Launch GUI application. - **-b, --bootstrap**: Create shortcut to launch GUI. - **--version**: Show version. ### Examples ```bash # Basic usage - create shortcut for a Python script pyshortcut /home/user/bin/myapp.py # Specify shortcut name and custom icon pyshortcut -n "My App" -i /path/to/icon.ico /home/user/bin/myapp.py # Create shortcut with script arguments (use quotes) pyshortcut -n "Data Processor" "/home/user/scripts/process.py --input data.csv" # Create GUI shortcut (no terminal window) pyshortcut -g -n "My GUI" /home/user/apps/guiapp.py # Place shortcut in a Desktop subfolder pyshortcut -f "Python Tools" -n "MyTool" /path/to/tool.py # Use specific Python executable pyshortcut -e /usr/bin/python3.11 -n "Py311 Script" /path/to/script.py # Create shortcut for a pip command pyshortcut -n "Update Packages" "_ -m pip install --upgrade pip" # Desktop only (no Start Menu) pyshortcut -d -n "Desktop Only" /path/to/script.py # Launch the GUI for interactive shortcut creation pyshortcut --wxgui # Create a desktop shortcut to the GUI itself (bootstrap) pyshortcut --bootstrap # Show version pyshortcut --version ``` ``` -------------------------------- ### Create a Shortcut for a Single Python Command Source: https://github.com/newville/pyshortcuts/blob/master/doc/python.md Wrap a single Python command in a shortcut. Use '_' or '{}' to indicate the current Python executable. This is useful for commands like upgrading packages. ```python import sys from pyshortcuts import make_shortcut pycmd = "_ -m pip install --upgrade pyshortcuts" make_shortcut(pycmd, name='Update Pyshortcuts') ``` -------------------------------- ### Python API: make_shortcut Source: https://github.com/newville/pyshortcuts/blob/master/README.md The make_shortcut function allows programmatic creation of shortcuts from within Python scripts. ```APIDOC ## Python API: make_shortcut ### Description Creates a shortcut programmatically using the pyshortcuts library. ### Request Example ```python from pyshortcuts import make_shortcut pycmd = "_ -m pip install --upgrade pyshortcuts" make_shortcut(pycmd, name='Update Pyshortcuts') ``` ``` -------------------------------- ### Python API: make_shortcut Source: https://github.com/newville/pyshortcuts/blob/master/README.md The `make_shortcut` function allows you to create shortcuts programmatically from within your Python scripts. ```APIDOC ## Python API: make_shortcut ### Description Creates a shortcut for a given script or command. The shortcut can be placed on the desktop, in the Start Menu, or both, with options for custom names, icons, and folders. ### Method `make_shortcut(script, name=None, description=None, icon=None, folder=None, terminal=True, desktop=True, startmenu=True, executable=None)` ### Parameters #### Arguments - **script** (str) - The script or command to be run. This can include command-line arguments. - **name** (str or None) - The name to use for the shortcut. Defaults to the script name. - **description** (str or None) - A longer description of the script. Defaults to the `name`. - **icon** (str or None) - Path to the icon file (.ico on Windows/Linux, .icns on macOS). Defaults to a Python icon. - **folder** (str or None) - The folder on the Desktop to place the shortcut in. Defaults to the Desktop itself. - **terminal** (bool) - Whether to run the shortcut in a terminal window. Defaults to True. - **desktop** (bool) - Whether to add the shortcut to the Desktop. Defaults to True. - **startmenu** (bool) - Whether to add the shortcut to the Start Menu. Defaults to True. Note: Start Menu is not available on macOS. - **executable** (str or None) - The name of the executable to use. Defaults to the Python executable used to create the shortcut. ### Request Example ```python from pyshortcuts import make_shortcut make_shortcut('/home/user/bin/myapp.py', name='MyApp', icon='/home/user/icons/myicon.ico', folder='MyApps', terminal=False) ``` ### Response This function does not return a value. It creates shortcut files on the file system. ``` -------------------------------- ### Fix wxPython display availability Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Add this snippet before the mainloop to bypass display availability checks on macOS. ```python import wx wx.PyApp.IsDisplayAvailable = lambda _: True ``` -------------------------------- ### debugtimer Source: https://context7.com/newville/pyshortcuts/llms.txt Creates a timing object for measuring and reporting execution time of code sections. Useful for profiling and identifying performance bottlenecks during development. ```APIDOC ## debugtimer ### Description Creates a timing object for measuring and reporting execution time of code sections. Useful for profiling and identifying performance bottlenecks during development. ### Method N/A (Class/Object) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from pyshortcuts import debugtimer, sleep import numpy as np # Create a debug timer dtmer = debugtimer('Performance Analysis', precision=4) # Mark timing points as code executes sleep(0.5) dtmer.add('Initialization complete') data = np.arange(10_000_000, dtype='float64') dtmer.add('Created data array') result = np.sqrt(data) dtmer.add('Computed square root') result = np.sum(result) dtmer.add('Summed results') # Print timing report dtmer.show() # Output: # # Performance Analysis 2024-04-27 17:31:12.3456 # +----------------------------------+------------------+------------------+ # | Message | Delta Time (s) | Total Time (s) | # +==================================+==================+==================+ # | start | 0.0000 | 0.0000 | # | Initialization complete | 0.5002 | 0.5002 | # | Created data array | 0.0276 | 0.5278 | # | Computed square root | 0.0201 | 0.5479 | # | Summed results | 0.0045 | 0.5524 | # +----------------------------------+------------------+------------------+ # Get report as string without printing report_text = dtmer.get_report() # Clear timer and start fresh (keeps title) dtmer.clear() # Verbose mode prints each message as it's added verbose_timer = debugtimer('Verbose Timer', verbose=True) verbose_timer.add('Step 1') # Prints: 'Step 1' verbose_timer.add('Step 2') # Prints: 'Step 2' ``` ### Response N/A ``` -------------------------------- ### Create Safe Filenames Source: https://context7.com/newville/pyshortcuts/llms.txt Converts a string into a safe filename by removing or replacing problematic characters, ensuring cross-platform compatibility. Spaces are converted to underscores by default. ```python from pyshortcuts import fix_filename # Remove special characters safe_name = fix_filename('My App: Version 2.0!') print(safe_name) # Output: 'My_App__Version_2.0_' # Spaces are converted to underscores by default safe_name = fix_filename('Hello World') print(safe_name) # Output: 'Hello_World' # Allow spaces in filename safe_name = fix_filename('Hello World', allow_spaces=True) print(safe_name) # Output: 'Hello World' # Multiple dots are collapsed (keeps only last extension) safe_name = fix_filename('file.backup.old.txt') print(safe_name) # Output: 'file_backup_old.txt' ``` -------------------------------- ### new_filename Source: https://context7.com/newville/pyshortcuts/llms.txt Generates a unique filename by incrementing a counter if the file already exists. Useful for avoiding overwrites when creating multiple files. ```APIDOC ## new_filename ### Description Generates a unique filename by incrementing a counter if the file already exists. Useful for avoiding overwrites when creating multiple files. ### Method N/A (Function) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from pyshortcuts import new_filename # Get a filename that doesn't exist filename = new_filename('output.txt') # If output.txt exists, returns 'output_001.txt' # If output_001.txt exists, returns 'output_002.txt' # Works with numbered files filename = new_filename('data.001') # If data.001 exists, returns 'data.002' # Numeric suffix is incremented intelligently filename = new_filename('report_005.csv') # If report_005.csv exists, returns 'report_006.csv' ``` ### Response N/A ``` -------------------------------- ### fix_filename Source: https://context7.com/newville/pyshortcuts/llms.txt Sanitizes strings to create safe, cross-platform compatible filenames. ```APIDOC ## fix_filename ### Description Converts a string into a safe filename by removing or replacing problematic characters. ### Parameters #### Request Body - **filename** (string) - Required - The string to sanitize - **allow_spaces** (boolean) - Optional - Whether to keep spaces instead of converting to underscores ``` -------------------------------- ### isotime Source: https://context7.com/newville/pyshortcuts/llms.txt Generates a formatted ISO timestamp with configurable precision and separators. ```APIDOC ## isotime ### Description Returns the current timestamp in ISO format with configurable precision and separator. ### Parameters #### Query Parameters - **sep** (string) - Optional - Separator between date and time (default is space) - **timespec** (string) - Optional - Precision level (e.g., 'milliseconds') - **dt** (datetime/int) - Optional - Specific datetime object or Unix timestamp to format ``` -------------------------------- ### Measure Code Execution Time Source: https://context7.com/newville/pyshortcuts/llms.txt Creates a timing object for measuring and reporting execution time of code sections. Useful for profiling and identifying performance bottlenecks during development. ```python from pyshortcuts import debugtimer, sleep import numpy as np # Create a debug timer dtimer = debugtimer('Performance Analysis', precision=4) # Mark timing points as code executes sleep(0.5) dtimer.add('Initialization complete') data = np.arange(10_000_000, dtype='float64') dtimer.add('Created data array') result = np.sqrt(data) dtimer.add('Computed square root') result = np.sum(result) dtimer.add('Summed results') # Print timing report dtimer.show() # Output: # # Performance Analysis 2024-04-27 17:31:12.3456 # +----------------------------------+------------------+------------------+ # | Message | Delta Time (s) | Total Time (s) | # +==================================+==================+==================+ # | start | 0.0000 | 0.0000 | # | Initialization complete | 0.5002 | 0.5002 | # | Created data array | 0.0276 | 0.5278 | # | Computed square root | 0.0201 | 0.5479 | # | Summed results | 0.0045 | 0.5524 | # +----------------------------------+------------------+------------------+ # Get report as string without printing report_text = dtimer.get_report() # Clear timer and start fresh (keeps title) dtimer.clear() # Verbose mode prints each message as it's added verbose_timer = debugtimer('Verbose Timer', verbose=True) verbose_timer.add('Step 1') # Prints: 'Step 1' verbose_timer.add('Step 2') # Prints: 'Step 2' ``` -------------------------------- ### Read Text File with Encoding Detection Source: https://context7.com/newville/pyshortcuts/llms.txt Reads a text file and returns its contents as a string with normalized line endings. Automatically detects file encoding using charset_normalizer. ```python from pyshortcuts import read_textfile # Read entire file content = read_textfile('/path/to/file.txt') # Read first N bytes content = read_textfile('/path/to/large_file.txt', size=1024) # Works with file-like objects with open('/path/to/file.txt', 'rb') as f: content = read_textfile(f) # Automatically handles different encodings (UTF-8, Latin-1, etc.) # Line endings (\r\n, \r) are normalized to \n # Returns string suitable for splitting with content.split('\n') ``` -------------------------------- ### Generate Unique Filename Source: https://context7.com/newville/pyshortcuts/llms.txt Generates a unique filename by incrementing a counter if the file already exists. Useful for avoiding overwrites when creating multiple files. ```python from pyshortcuts import new_filename # Get a filename that doesn't exist filename = new_filename('output.txt') # If output.txt exists, returns 'output_001.txt' # If output_001.txt exists, returns 'output_002.txt' # Works with numbered files filename = new_filename('data.001') # If data.001 exists, returns 'data.002' # Numeric suffix is incremented intelligently filename = new_filename('report_005.csv') # If report_005.csv exists, returns 'report_006.csv' ``` -------------------------------- ### Debug runtime of code sections Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md Creates a DebugTimer object to measure and report the runtime of different code sections within a function or script. ```python import numpy as np from pyshortcuts import debugtimer, sleep SHOW_TIMING = True dtimer = debugtimer('test timer', precision=4) sleep(0.50) dtimer.add('slept for 0.500 seconds') nx = 10_000_000 x = np.arange(nx, dtype='float64')/3.0 dtimer.add(f'created numpy array len={nx}') s = np.sqrt(x) dtimer.add('took sqrt') if SHOW_TIMING: dtimer.show() ``` -------------------------------- ### read_textfile Source: https://context7.com/newville/pyshortcuts/llms.txt Reads a text file and returns its contents as a string with normalized line endings. Automatically detects file encoding using charset_normalizer. ```APIDOC ## read_textfile ### Description Reads a text file and returns its contents as a string with normalized line endings. Automatically detects file encoding using charset_normalizer. ### Method N/A (Function) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from pyshortcuts import read_textfile # Read entire file content = read_textfile('/path/to/file.txt') # Read first N bytes content = read_textfile('/path/to/large_file.txt', size=1024) # Works with file-like objects with open('/path/to/file.txt', 'rb') as f: content = read_textfile(f) # Automatically handles different encodings (UTF-8, Latin-1, etc.) # Line endings (\r\n, \r) are normalized to \n # Returns string suitable for splitting with content.split('\n') ``` ### Response N/A ``` -------------------------------- ### Format Floating-Point Numbers Source: https://context7.com/newville/pyshortcuts/llms.txt Formats floating-point numbers with a fixed output length while maximizing precision. Produces consistent column widths in tables while showing as many significant digits as possible. ```python from pyshortcuts import gformat # Default length of 11 characters print(gformat(13.1153846)) # Output: ' 13.1153846' print(gformat(10.2)) # Output: ' 10.2000000' print(gformat(-0.00000136608)) # Output: '-1.36608e-6' # Custom length print(gformat(-0.00000136608, length=15)) # Output: '-0.000001366077' print(gformat(0.000075, length=7)) # Output: ' 7.5e-5' # Large numbers print(gformat(1234567.89, length=11)) # Output: ' 1234567.89' print(gformat(1.23e15, length=11)) # Output: ' 1.2300e+15' # Useful for creating aligned tables values = [3.14159, 2.71828, 1.41421, 0.00001] for v in values: print(f"|{gformat(v, length=12)}|") # Output: # | 3.14159000| # | 2.71828000| # | 1.41421000| # | 0.00001000| ``` -------------------------------- ### Handle wxPython display errors on macOS Source: https://github.com/newville/pyshortcuts/blob/master/doc/pyshortcut_app.md Error message encountered when running wxPython apps with Anaconda Python on macOS. ```default ~> python my_wxpython_app.py This program needs access to the screen. Please run with a Framework build of python, and only when you are logged in on the main display of your Mac. ``` -------------------------------- ### gformat Source: https://context7.com/newville/pyshortcuts/llms.txt Formats floating-point numbers with fixed output length while maximizing precision. Produces consistent column widths in tables while showing as many significant digits as possible. ```APIDOC ## gformat ### Description Formats floating-point numbers with fixed output length while maximizing precision. Produces consistent column widths in tables while showing as many significant digits as possible. ### Method N/A (Function) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from pyshortcuts import gformat # Default length of 11 characters print(gformat(13.1153846)) # Output: ' 13.1153846' print(gformat(10.2)) # Output: ' 10.2000000' print(gformat(-0.00000136608)) # Output: '-1.36608e-6' # Custom length print(gformat(-0.00000136608, length=15)) # Output: '-0.000001366077' print(gformat(0.000075, length=7)) # Output: ' 7.5e-5' # Large numbers print(gformat(1234567.89, length=11)) # Output: ' 1234567.89' print(gformat(1.23e15, length=11)) # Output: ' 1.2300e+15' # Useful for creating aligned tables values = [3.14159, 2.71828, 1.41421, 0.00001] for v in values: print(f"|{gformat(v, length=12)}|") # Output: # | 3.14159000| # | 2.71828000| # | 1.41421000| # | 0.00001000| ``` ### Response N/A ``` -------------------------------- ### Format floating-point numbers Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md Formats a floating-point number to a string of a specified length, maximizing precision and retaining trailing zeros. ```python from pyshortcuts import gformat >>> gformat(1023/78, length=11) ' 13.1153846' >>> gformat(10.2, length=11) ' 10.2000000' >>> gformat(-1/732023, length=11)) '-1.36608e-6' >>> gformat(-1/732023, length=15) '-0.000001366077' >>> gformat(6/80030, length=7) ' 7.5e-5' ``` -------------------------------- ### High-precision sleep function Source: https://github.com/newville/pyshortcuts/blob/master/doc/utilities.md Implements a more accurate sleep function than Python's time.sleep by using perf_counter. ```python from time import perf_counter def sleep(duration): "more accurate sleep()" end = perf_counter() + duration while perf_counter() < end: pass ``` -------------------------------- ### sleep Source: https://context7.com/newville/pyshortcuts/llms.txt A higher-precision sleep function that uses busy-waiting. Python's `time.sleep()` can be inaccurate by 10+ milliseconds; this function provides more precise timing when needed. ```APIDOC ## sleep ### Description A higher-precision sleep function that uses busy-waiting. Python's `time.sleep()` can be inaccurate by 10+ milliseconds; this function provides more precise timing when needed. ### Method N/A (Function) ### Endpoint N/A ### Parameters N/A ### Request Example ```python from pyshortcuts import sleep import time # High-precision sleep for 0.1 seconds sleep(0.1) # Compare with standard sleep start = time.perf_counter() time.sleep(0.01) # May sleep 0.015-0.025 seconds standard_sleep = time.perf_counter() - start start = time.perf_counter() sleep(0.01) # Much closer to 0.01 seconds precise_sleep = time.perf_counter() - start print(f"Standard sleep: {standard_sleep:.6f}s") print(f"Precise sleep: {precise_sleep:.6f}s") # Note: Uses busy-waiting (CPU-intensive) - use only when precision matters ``` ### Response N/A ``` -------------------------------- ### High-Precision Sleep Function Source: https://context7.com/newville/pyshortcuts/llms.txt A higher-precision sleep function that uses busy-waiting. Python's `time.sleep()` can be inaccurate by 10+ milliseconds; this function provides more precise timing when needed. ```python from pyshortcuts import sleep import time # High-precision sleep for 0.1 seconds sleep(0.1) # Compare with standard sleep start = time.perf_counter() time.sleep(0.01) # May sleep 0.015-0.025 seconds standard_sleep = time.perf_counter() - start start = time.perf_counter() sleep(0.01) # Much closer to 0.01 seconds precise_sleep = time.perf_counter() - start print(f"Standard sleep: {standard_sleep:.6f}s") print(f"Precise sleep: {precise_sleep:.6f}s") # Note: Uses busy-waiting (CPU-intensive) - use only when precision matters ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.