[英]Is it possible to import a python file from outside the directory the main file is in?
I have a file structure that looks like this:我有一个看起来像这样的文件结构:
Liquid
|
[Truncate]
|_General_parsing
[Truncate]
.....|_'__init__.py'
.....|_'Processer.py'
.....|'TOKENIZER.py'
|_'__init__.py'
|_'errors.py'
[Truncate]
I want to import errors.py
from Processer.py
.我想从
Processer.py
导入errors.py
。 Is that possible?那可能吗? I tried to use this:
我试着用这个:
from ..errors import *; error_manager = errorMaster()
Which causes this:这导致了这个:
Traceback (most recent call last):
File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 17, in <module>
from ..errors import *; error_manager = errorMaster()
ImportError: attempted relative import with no known parent package
[Finished in 0.125s]
I've seen this post , but it's no help, even if it tries to solve the same ImportError
.我看过这篇文章,但它没有帮助,即使它试图解决相同的
ImportError
。 This isn't, either (at least not until I edited it), since I tried: 这也不是(至少在我编辑它之前不是),因为我尝试过:
import sys
sys.path.insert(1, '../Liquid')
from errors import *; error_manager = errorMaster()
That gives这给了
Traceback (most recent call last):
File "/Users/MYNAME/projects/Liquid/General_parsing/Processer.py", line 19, in <module>
from errors import *; error_manager = errorMaster()
ModuleNotFoundError: No module named 'errors'
[Finished in 0.162s]
EDIT: Nevermind!编辑:没关系! I solved it!
我解决了! I just need to add
..
to sys.path!我只需要将
..
添加到 sys.path! Or .
或
.
if ..
doesn't solve your problem.如果
..
不能解决您的问题。 But if those don't solve your problem: use some pathlib
(came in python3.4+) magic and do:但是,如果这些不能解决您的问题:使用一些
pathlib
(来自 python3.4+)魔术并执行以下操作:
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).parent))
or, if you want to use os
: (gotten from this StackOverflow answer)或者,如果你想使用
os
:(从这个StackOverflow 答案中获得)
import os
os.path.join(os.path.dirname(__file__), '..')
I solved it!我解决了! I have to add
..
to sys.path instead我必须将
..
添加到 sys.path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.