简体   繁体   English

如何组织一个可以作为__main__程序运行脚本的python模块?

[英]how to organize a python module that scripts can be run as __main__ program?

I'm starting a project in python, the code structure now as below: 我正在用python启动一个项目,现在的代码结构如下:

project/
        __init__.py
        a.py
        b.py
        mainA.py
        utilities/
                   __init__.py
                   mainB.py
                   c.py

The __init__ files are all blank. __init__文件全部为空。

I want to run utilities/mainB.py as a program(using something like python main.py ), and mainB needs to import a.py and b.py . 我想将utilities/mainB.py作为程序运行(使用类似python main.py类的东西),并且mainB需要导入a.pyb.py So I tried from .. import a and some other approaches, but the import failed. 所以我尝试了from .. import a和其他方法,但是import失败。 The error information is: 错误信息是:

ValueError: Attempted relative import in non-package ValueError:尝试非包中的相对导入

So here comes the questions: 因此,出现了以下问题:

  1. how to fix mainB.py so it can be run as a main program? 如何修复mainB.py ,使其可以作为主程序运行?
  2. mainA.py can be run as main program now, it also imports a.py and b.py (using import a and import b ). mainA.py现在可以作为主程序运行,它也可以导入a.pyb.py (使用import aimport b )。 I think the code structure may become more complex. 我认为代码结构可能会变得更加复杂。 Say, if mainA.py has to import a module from project/some/directory , how can I do that? 说,如果mainA.py必须从project/some/directory导入模块,我该怎么做?

See this previous question . 请参阅前面的问题 You have two options. 您有两个选择。 One is to use the __package__ attribute as described in PEP 366 to set the relative name of your modules. 一种是使用PEP 366中所述的__package__属性来设置模块的相对名称。 The other is to execute your scripts as modules (using the -m flag to the interpreter) instead of running them directly as scripts. 另一种方法是将脚本作为模块执行(使用解释器的-m标志),而不是直接将其作为脚本运行。

You could use Python's built-in module-running functionality ( python -m <module> ). 您可以使用Python的内置模块运行功能( python -m <module> )。

python -m project.utilities.mainB

This allows you to write mainB normally as part of the package, so relative and absolute imports will both work correctly. 这使您可以将mainB作为包的一部分正常编写,因此相对导入和绝对导入都可以正常工作。

For an in-depth discussion of this functionality, see PEP-338 . 有关此功能的深入讨论,请参阅PEP-338

您应该在PYTHON_PATH中添加“ project”目录,然后在mainB.py中添加:

from project import a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM