[英]python, import file under current folder from a file under other directory
I have a package which intends to import a file that user (me) provides 我有一个软件包,打算导入用户(我)提供的文件
In c:\\lib \\calc.py 在c:\\ lib \\ calc.py
# some codes to find which file to import
filename = "A"
__import__(filename)
...
And I have a file c:\\scripts \\A.py 我有一个文件c:\\ scripts \\ A.py
Note A.py is in a different folder than calc.py. 注意A.py与calc.py位于不同的文件夹中。 Now I'm supposed to do this under command window 现在我应该在命令窗口下执行此操作
cd C:\scripts
python c:\lib\calc.py
but I get an error message 但我收到一条错误消息
No module named A
A.py is in the current folder, why does python fail to find it? A.py在当前文件夹中,为什么python无法找到它? How can I make A.py available? 如何使A.py可用?
Thanks. 谢谢。
You can add the path to your scripts directory in your script calc.py so it can find the A.py module. 您可以在脚本calc.py中将路径添加到脚本目录,以便它可以找到A.py模块。
import sys
sys.path.append('C:\scripts')
If you are on Python version 2.7 or newer you can use the importlib
package. 如果您使用的是Python 2.7或更高版本,则可以使用importlib
软件包。 The import_module
function can accept an absolute path which, IIRC, does not need to be on your PYTHONPATH. import_module
函数可以接受绝对路径IIRC,该绝对路径不必位于您的PYTHONPATH上。
import importlib
mod = importlib.import_module(filepath)
Or, if you wanted to manually do the work yourself (or if you are using Python 2.6 or earlier), you can use the imp
package directly: 或者,如果您想自己手动进行工作(或者如果您使用的是Python 2.6或更早版本),则可以直接使用imp
包:
import imp
mod = imp.load_module(imp.find_module(filename, filepath))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.