PyInstaller编译保留外部模块可编辑性的技术问题求助
lexer.py to Keep It Editable for FSCMD I get exactly what you're trying to achieve here—you want your compiled FSCMD executable to depend on the external, editable lexer.py file, just like a regular Python script would, instead of having PyInstaller bundle it into the executable (which makes it unmodifiable after packaging). Let's break down how to fix this step by step:
1. Exclude lexer.py from PyInstaller's Packaging
PyInstaller automatically collects all imported modules to bundle into the executable. We need to explicitly tell it to skip lexer.py.
Option 1: Command-Line Argument
When running PyInstaller, add the --exclude-module flag:
pyinstaller --exclude-module lexer your_main_fscmd_script.py
Option 2: Modify the .spec File (Recommended for Persistent Config)
If you're using a .spec file (generated with pyinstaller --name fscmd your_main_script.py), update the excludes list in the Analysis section:
a = Analysis( ['your_main_fscmd_script.py'], pathex=[], binaries=[], datas=[], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=['lexer'], # Add this line to exclude the module noarchive=False, ) # Rest of the .spec file remains the same
2. Ensure Runtime Dependencies on External lexer.py
Excluding the module isn't enough—we need to make sure the executable looks for the external lexer.py at runtime, and fails gracefully if it's missing (just like regular Python does).
Update your main script's import logic to explicitly check for the external file:
import os import sys # Add the executable's directory to Python's path (so it can find lexer.py if they're in the same folder) exe_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path.insert(0, exe_dir) try: import lexer except ImportError as original_error: # Raise a clear error message for users raise ImportError( "Error: Could not find `lexer.py`! Please ensure it's placed in the same directory as this executable. " "`lexer.py` must remain editable to keep FSCMD fully open-source." ) from original_error # Use lexer as you normally would # Example: lexer.process_input("your command here")
3. Verify the Behavior
After packaging:
- Place the compiled executable and
lexer.pyin the same directory- Run the executable: It works normally, using your editable
lexer.py
- Run the executable: It works normally, using your editable
- Remove or rename
lexer.py- Run the executable: It throws an
ImportErrorexactly like a regular Python script would, confirming it's dependent on the external file.
- Run the executable: It throws an
To tie this back to your example:
In a regular Python environment:
import test_file test_file.test_function(test_parameter)This throws an error if
test_file.pyis missing. With the steps above, your compiled FSCMD will behave identically—it will only run iflexer.pyexists externally, keeping the file editable and true to your open-source goal.
内容的提问来源于stack exchange,提问作者FaranAiki

