简体   繁体   English

在另一个文件夹中导入python3

[英]imports python3 in another folder

When I run launch.py it fails and when I run main.py directly it works. 当我运行launch.py​​时它会失败,当我直接运行main.py时它会起作用。 launch.py just imports and runs main.py. launch.py​​只是导入并运行main.py. Why? 为什么?

├── dir
│   ├── bla.py
│   ├── __init__.py
│   └── main.py
├── __init__.py
└── launch.py

launch.py
---------
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-

    from dir import main
    main.main()

main.py
-------

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import bla
    bla.pront()


bla.py
------

def pront():
    print('pront')

EDITED: 编辑:

enter image description here 在此输入图像描述

Using your layout and with the following files, we don't have problems. 使用您的布局和以下文件,我们没有问题。

launch.py launch.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dir import main

if __name__ == "__main__":
   main. main()

main.py main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
    from . import bla
except:
    import bla

def main():
    bla.pront()

if __name__ == "__main__":
    main()

The try ... except structure is used in case the main.py was used inside or outside the package. 如果在包内部或外部使用main.py,则使用try ... except结构。

Of course, there is a lot of info about it. 当然,有很多关于它的信息。 You can start with this . 你可以从这开始。

I believe I see the answer... 我相信我看到了答案......
You have not defined main, perhaps try that. 你没有定义main,也许尝试一下。 The reason why it works when called directly is because Python scripts are run in the order in which functions appear unless a specific function is called. 直接调用它的原因是因为Python脚本按函数出现的顺序运行,除非调用特定的函数。

Try changing main.py to 尝试将main.py更改为

import bla
def mainfunction():
    bla.pront()

Then change launch.py to 然后将launch.py​​更改为

import main
main.mainfunction()

I hope this helps! 我希望这有帮助! :) :)

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

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