Python path and parameter practical operations set (FAQ)
In daily Python development, operations such as path splicing and command line parameter parsing can be seen everywhere. This article compiles solutions to 5 high-frequency problems and gives best practice suggestions in a production environment. All code is compatible with Python 3.6+ (taking into account mainstream production environments).
Q1: How to get the current working directory?
The Current Working Directory refers to the directory where the script is executed, not the storage path of the script file itself - this is often confused, so be clear about this first.
Method selection and code
- New projects are given priority
pathlib: What is returned isPathObject instead of ordinary string, subsequent path concatenation and parsing are safer and more readable. - ** Try not to use it
os.path.abspath('.')**: It depends on the current directory symbol.parsing, which is slightly less efficient and less semantic thangetcwd()clear. - Use only in ad hoc scripts that need compatibility with older Python versions
os.getcwd()。 :::
Q2: How to obtain the file information of the currently executed module?
The "module file" here refers to the currently running.pySource file**. It should be noted that in REPL, Jupyter Notebook or packaged environment,__file__Variables will behave differently.
Core operation code
:::note Special environment instructions
- In Python REPL/Jupyter Notebook:
__file__The variable does not exist, and an error will be reported if used directly. - After packaging using PyInstaller/Nuitka:
__file__It may point to the temporary decompression directory. In this case, you need to usesys._MEIPASSto get the real resource path (but this variable only exists in the packaging environment). - Must be called
resolve(): It will automatically expand relative paths and symbolic links (soft links) to avoid errors during subsequent path splicing. :::
Q3: How to handle command line parameters?
Command line parameters are an important way to pass configuration to the script externally. Python provides a simple and fastsys.argvand professionally scalableargparseTwo options.
Solution selection and code
Option 1: Simple and fast (suitable for small scripts with 1~3 unnamed parameters)
Option 2: Professional extensibility (Python official built-in module, recommended)
:::tip Advanced alternative library
- Pursuing a minimalist and friendly CLI interface: use
click(Based on decorators, the writing method is closer to ordinary functions). - For strong type hints and automatic documentation: use
typer(based onclick, providing built-in type checking and help information generation). :::
Q4: How to get the path of the current Python interpreter?
Through the interpreter path, you can quickly determine whether you are currently using system Python, virtual environment Python, or Python in the conda environment.
Code implementation
:::note Differences in packaging environment
After packaging using PyInstaller/Nuitka,sys.executablewill point to the generated.exe(Windows) or executable (Linux/macOS) instead of the original Python interpreter. If you need to find packaged resource files, you should usesys._MEIPASS(Only valid after packaging).
Q5: How to write cross-platform path code?
Windows uses backslashes\, while Linux/macOS uses forward slashes/. Manually splicing paths is not only cumbersome, but also highly error-prone.pathlibIt is the perfect tool to solve this problem.
Core cross-platform code
:::tip Must remember to avoid pitfalls
- Never manually splice backslashes or forward slashes: leave it all to
pathlibof/operator. - Use as much as possible
PathObject delivery path: Do not convert to a string prematurely unless the third-party library explicitly requires a string to be passed in. Path.home()It will obtain the user's home directory, work correctly on different operating systems, and is the first choice for storing configuration files. :::
Summary of this FAQ
Finally, we outline the must-use specifications in the production environment for you, and it is recommended to develop proficient usage habits:
- All path operations: Use uniformly
pathlib(Farewell graduallyos.pathFamily bucket). - Command line parameters: When there are more than 3 parameters, or when named parameters or Boolean switches are needed, use them directly
argparse。 - Special Environment (REPL/Packaging): Judge in advance
__file__orsys._MEIPASSWhether the variable exists. - Cross-platform: Manual splicing of path separators is strictly prohibited, so
pathlibAutomatic processing.
Hopefully this FAQ will help you write more robust and clear Python code. If it is helpful to you, please share it with other friends!

