简体   繁体   English

Python模块的相对路径和顶级脚本

[英]Python module relative path and top-level script

I have the following directory structure 我有以下目录结构

Root/
    Main.py
    /Controller->
        /MotorController->
            MotorController.py
            __init__.py
    /Tools->
        test.py

Now Tools/test.py have some test code that basically imports MotorController.py using relative path like the following 现在Tools / test.py具有一些测试代码,基本上使用如下所示的相对路径导入MotorController.py

Tools/test.py from ..Controller.MotorController.MotorController import * 来自..Controller.MotorController.MotorController导入的Tools / test.py *

This gives an error that relative path cannot be used on non-package. 这给出了一个错误,即相对路径不能在非包上使用。 Moving the test.py to the Root directory solves the problem but I really want my scripts to be in the Tools directory. 将test.py移至Root目录可以解决此问题,但我确实希望脚本位于Tools目录中。 How do I do this ?. 我该怎么做呢 ?。

This is a related question; 这是一个相关的问题; Say I make a package MotorController.MotorController.py like above that works on a particular robot. 假设我制作了一个像上面这样的程序包MotorController.MotorController.py,它可以在特定的机器人上工作。 Now I want to have some calibration script that only works on that particular robot and hence I was planning to put that script in the same directory as MotorController.py. 现在,我想拥有一些仅适用于该特定机器人的校准脚本,因此我打算将该脚本放置在与MotorController.py相同的目录中。 But it seems like one can't run a script from the same directory as the Package due to relative path and etc. Is there a way around or what is the general principle in such cases. 但是由于相对路径等原因,似乎不能在与Package相同的目录中运行脚本。在这种情况下,有没有解决的办法或一般原则是什么?

To make a package of a folder you must include and __init__.py file (can be empty). 要制作一个文件__init__.py您必须包含__init__.py文件(可以为空)。
So you should add one of these files in each folder of your Root structure. 因此,您应该在根结构的每个文件夹中添加这些文件之一。

You need a file to indicate that the folder is a python package. 您需要一个文件来指示该文件夹是python软件包。

the standard is a (often empty) __init__.py file, note that there are 4 underscores total. 标准是__init__.py文件(通常为空),请注意总共有4个下划线。

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

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