从一个目录中调用目录外的文件 - Python

3

我有一个包含所有文件的目录:

myDirectory/
    directory1/
        importantFile.py
    Output.py

我该如何在不将Output.py放在同一目录下的情况下,从importantFile.py中导入Output.py?
importantFile.py
import Output
Output.write('This worked!')

Output.py

class Output():
    def writeOutput(s):
        print s

我可以有一个例子吗? - Avid Programmer
2
请定义您所说的“调用”,它是指导入吗?我将为Output和ImportantFile提供一些简要内容,以解释您想要做什么。 - Bruce
1
你所说的“call”,是指导入(import)吗?还是指subprocess.call()函数? - Morgan Thrapp
使用相对路径 "../Output.py"。 - pzelasko
我所说的“call”是指导入。 - Avid Programmer
3个回答

1
如果“call”被导入,在Output.py中。
import sys
import os.path
# change how import path is resolved by adding the subdirectory
sys.path.append(os.path.abspath(os.getcwd()+'/directory1'))
import importantFile

importantFile.f()

sys.path 包含了查找模块的路径列表,详情请参见https://docs.python.org/2/library/sys.html


0
另一种方法是使用相对符号,要导入的Python文件应该在一个包中。
您需要通过放置一个init.py文件来将目录变成Python包。
请查看此链接中的“包”部分。

https://docs.python.org/2/tutorial/modules.html


0
import sys
sys.path.append('/full/path/to/use')
global exist_importedname
exist_importedname = True
try:
    import myimport
except ImportError as e:
    exist_importedname = False
    print (e.message)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接