如何用极简代码封装Python可执行文件并复用所有argparse参数
问题
我路径下有一个名为fastq_preprocessor.py的Python可执行文件,该程序包含short、long子模块,使用argparse处理命令行参数。我想要创建一个名为fastq_preprocessor的封装程序(与原文件同目录),调用原程序并原生复用所有命令行参数,且代码尽可能精简。
我尝试了一段封装代码,执行./fastq_preprocessor -h时可正常显示主帮助信息,但执行./fastq_preprocessor short -h或./fastq_preprocessor long -h时,返回的仍是主程序帮助信息,而非对应子模块的帮助信息。
原程序代码
#!/usr/bin/env python # Built-ins import os, sys, argparse, importlib # Version __program__ = os.path.split(sys.argv[0])[-1] __version__ = "2023.11.28" # Accepted modules accepted_programs = ["short", "long"] script_directory = os.path.dirname(os.path.abspath( __file__ )) # Controller def main(argv=None): parser = argparse.ArgumentParser(prog="fastq_preprocessor",description="A fastq preprocessor for short and long read sequencing. Optional contamination removal.", add_help=True) parser.add_argument("program", choices=accepted_programs, help="`fastq_preprocessor` program for preprocessing. `short` for Illumina and `long` for ONT/PacBio.") parser.add_argument("-c", "--citation", action='version', help="Show full citation (doi: 10.1186/s12859-022-04973-8)", version="Espinoza JL, Dupont CL.\nVEBA: a modular end-to-end suite for in silico recovery, clustering, and analysis of prokaryotic, microeukaryotic, and viral genomes from metagenomes.\nBMC Bioinformatics. 2022 Oct 12;23(1):419. doi: 10.1186/s12859-022-04973-8. PMID: 36224545.") parser.add_argument("-v", "--version", action='version', version="{} v{}".format(__program__, __version__)) opts = parser.parse_args(argv) return opts.program # Initialize if __name__ == "__main__": # Check version python_version = sys.version.split(" ")[0] condition_1 = int(python_version.split(".")[0]) == 3 condition_2 = int(python_version.split(".")[1]) >= 6 assert all([condition_1, condition_2]), "Python version must be >= 3.6. You are running: {}\n{}".format(python_version, sys.executable) # Get the algorithm program = main([sys.argv[1]]) module = importlib.import_module("fastq_preprocessor_{}".format(program)) module.main(sys.argv[2:])
尝试的封装代码
#!/usr/bin/env python # Built-ins import os, sys, importlib # Version __program__ = os.path.split(sys.argv[0])[-1] __version__ = "2023.11.28" # Accepted modules script_directory = os.path.dirname(os.path.abspath( __file__ )) if __name__ == "__main__": module = importlib.import_module("fastq_preprocessor") # Call the main function with the command line arguments module.main(sys.argv[1:])
异常输出示例
(base) jespinozlt2-osx:fastq_preprocessor jespinoz$ ./fastq_preprocessor -h usage: fastq_preprocessor [-h] [-c] [-v] {short,long} A fastq preprocessor for short and long read sequencing. Optional contamination removal. positional arguments: {short,long} `fastq_preprocessor` program for preprocessing. `short` for Illumina and `long` for ONT/PacBio. optional arguments: -h, --help show this help message and exit -c, --citation Show full citation (doi: 10.1186/s12859-022-04973-8) -v, --version show program's version number and exit (base) jespinozlt2-osx:fastq_preprocessor jespinoz$ ./fastq_preprocessor short -h usage: fastq_preprocessor [-h] [-c] [-v] {short,long} A fastq preprocessor for short and long read sequencing. Optional contamination removal. positional arguments: {short,long} `fastq_preprocessor` program for preprocessing. `short` for Illumina and `long` for ONT/PacBio. optional arguments: -h, --help show this help message and exit -c, --citation Show full citation (doi: 10.1186/s12859-022-04973-8) -v, --version show program's version number and exit (base) jespinozlt2-osx:fastq_preprocessor jespinoz$ ./fastq_preprocessor long -h usage: fastq_preprocessor [-h] [-c] [-v] {short,long} A fastq preprocessor for short and long read sequencing. Optional contamination removal. positional arguments: {short,long} `fastq_preprocessor` program for preprocessing. `short` for Illumina and `long` for ONT/PacBio. optional arguments: -h, --help show this help message and exit -c, --citation Show full citation (doi: 10.1186/s12859-022-04973-8) -v, --version show program's version number and exit
解决方案
问题出在原程序的核心逻辑都在if __name__ == "__main__"代码块中,而你之前的封装代码只调用了原程序的main函数,没有触发这部分处理子模块参数和帮助信息的逻辑。原程序的main函数仅负责解析第一个参数(子模块名称)并返回,真正加载子模块、处理后续参数的流程都在__main__代码块内。
精简版封装代码
#!/usr/bin/env python import sys import os # 模拟原程序被直接执行的场景 sys.argv[0] = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fastq_preprocessor.py") __name__ = "__main__" # 导入原程序,自动触发其__main__逻辑 import fastq_preprocessor
解释
当设置__name__ = "__main__"后,导入fastq_preprocessor模块时,原程序的if __name__ == "__main__"代码块会被执行,完整复现原程序的执行流程:
- 检查Python版本是否符合要求
- 调用
main函数解析第一个参数(子模块名) - 加载对应的
short或long子模块 - 将剩余命令行参数传给子模块的
main函数,此时子模块的argparse会正常处理-h并显示对应帮助信息
这样既实现了参数的完全复用,又保持了封装代码的精简性。
内容的提问来源于stack exchange,提问作者O.rka
相关产品推荐
相关产品推荐

