我正在研究由许多脚本组成的Python模块。最终目标是使该模块中的功能import
在进行交互工作时可通过语句导入,并通过命令行参数使模块的某些部分可执行。
可以使用以下命令运行模块:
python -m ./my_module --help
# No -m switch
python ./my_module --help
在此答案之后,我想了解-m
开关__main__.py
与__init__.py
文件之间的关系。当前结构如下
__main__.py
# Shebang line
###########
# Modules #
###########
import argparse
import logging
import tempfile
###################
# Package modules #
###################
from utilities import check_directory_access
# ...
#################
# Run functions #
#################
def run(args):
"""Run all functions with provided arguments"""
# Start logging configuration
# If file is not provided use temporary file
if args.log_file is None:
args.log_file = tempfile.NamedTemporaryFile(delete=False,
prefix='my_module',
suffix='.log').name
# Create handlers: console
# logging configuration
logging.shutdown()
def main():
"""Process arguments and run main function"""
parser = argparse.ArgumentParser(description='Dop stuff module',
epilog='Epilog')
parser.add_argument("-t", "--tables", nargs='+', dest='tables',
help="List tables to refresh", type=str)
parser.add_argument("-l", "--log-file", dest='log_file',
type=str, help="Log file")
parser.set_defaults(func=run)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
__init__.py
###################
# Package modules #
###################
from .utilities import check_directory_access
# Other components
运行:
python -m my_module --help
退货
ImportError:没有名为“实用程序”的模块
而
python my_module --help
没问题
python my_module
和python -m my_module
工作。import my_module
交互工作时不中断(奖励)首先运行而不调用python
解释器./my_module --help
。我不确定如何用tree做到这一点:
|-- my_module
| |-- my_module.py
| |-- __init__.py
| |-- __main__.py
| |-- module_component_A.py
| |-- utilities.py
是否有特定内容应该去my_module.py
?
Python 3没有隐含的相对导入。使用绝对或显式相对导入:
from .utilities import check_directory_access
from my_module.utilities import check_directory_access
这使您的包裹可与-m
交换机配合使用。它还允许进行import my_module
交互式会话。
存储为文件夹的裸包无法直接执行。这是由于操作系统本身。如果要避免显式调用python,则必须创建一个运行程序包的可执行文件。
可以将软件包存储为可执行的zip文件,或者创建运行软件包的脚本。
#!/usr/bin/env python3
import my_module.__main__
请注意,后者要求您安装模块或直接在脚本附近。如果您的模块可以安装,则console_scripts
entry_point
允许自动创建此类脚本。
您不应该将脚本驻留在软件包中-这需要您更改sys.path
到父目录,这可能导致重复的模块。例如,utilities.py
将作为单独的模块my_module.utilities
和提供 utilities
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句