简体   繁体   English

来自相对文件夹的Python导入模块

[英]Python import module from relative folder

i'm creating a python program, and i want to split it up into seperate files. 我正在创建一个python程序,我想把它拆分成单独的文件。 I'm using import to do this, but its not working (specifically, a variable is stored in one python file, and its not being read by the main one. 我正在使用import来执行此操作,但它不起作用(具体地说,变量存储在一个python文件中,而不是由主要文件读取。

program /

     main.py

     lib /

          __init__.py

          config.py

          functions.py

I have in main.py: 我在main.py中:

import lib.config
import lib.functions
print(main)

and config.py has 和config.py有

 main = "hello"

I should be getting the output "hello", when i'm executing the file main.py, but i'm not. 我正在执行输出“hello”,当我执行文件main.py时,但我不是。 I have the same problem with functions stored in functions.py 我对functions.py中存储的函数有同样的问题

Any help would be great, 任何帮助都会很棒,

Importing the module with a simple import statement does not copy the names from that module into your own global namespace. 用一个简单的导入模块import语句从该模块的名称复制到自己的全局命名空间。

Either refer to the main name through attribute access: 通过属性访问引用main名称:

print(lib.config.main)

or use the from ... import ... syntax: 或使用from ... import ...语法:

from lib.config import main

instead. 代替。

You can learn more about how importing works in the Modules section of the Python tutorial . 您可以在Python教程Modules部分中了解有关导入如何工作的更多信息。

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

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