如何在 Python 中导入文件?我要导入:
- 一个文件(例如
file.py
) - 一个文件夹
- 根据用户输入在运行时动态生成文件
- 文件的一个特定部分(例如单个函数)
原文由 Tamer 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何在 Python 中导入文件?我要导入:
file.py
)原文由 Tamer 发布,翻译遵循 CC BY-SA 4.0 许可协议
不要草率地选择第一个适合你的导入策略,否则当你发现它不符合你的需求时,你将不得不重写代码库。
我将从解释最简单的示例 #1 开始,然后我将转向最专业和最强大的示例 #7
示例 1,使用 python 解释器导入 python 模块:
def what_does_the_fox_say():
print("vixens cry")
el@apollo:/home/el/foo$ python
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
>>> import fox
>>> fox.what_does_the_fox_say()
vixens cry
>>>
您通过 python 解释器导入了 fox,从 fox.py 中调用了 python 函数 what_does_the_fox_say()
。
示例 2,在脚本中使用 execfile
或( exec
在 Python 3 中)以执行其他 python 文件:
def moobar():
print("hi")
execfile("/home/el/foo2/mylib.py")
moobar()
el@apollo:/home/el/foo$ python main.py
hi
函数 moobar 从 mylib.py 导入并在 main.py 中可用
示例 3,使用 from … import … 功能:
def question():
print "where are the nuclear wessels?"
from chekov import question
question()
el@apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
如果您在 chekov.py 中定义了其他函数,它们将不可用,除非您 import *
示例 4,如果 riaa.py 位于与导入位置不同的文件位置,则导入它
def watchout():
print "computers are transforming into a noose and a yoke for humans"
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *
watchout()
el@apollo:/home/el/foo4$ python main.py
computers are transforming into a noose and a yoke for humans
从不同的目录导入外部文件中的所有内容。
例5,使用 os.system("python yourfile.py")
import os
os.system("python yourfile.py")
示例 6,通过搭载 python startuphook 导入您的文件:
更新: 这个例子过去适用于 python2 和 3,但现在只适用于 python2。 python3 摆脱了这个用户 startuphook 功能集,因为它被低技能的 python 库编写者滥用,使用它在所有用户定义的程序之前不礼貌地将他们的代码注入全局命名空间。如果你想让它适用于 python3,你必须更有创意。如果我告诉您如何操作,python 开发人员也会禁用该功能集,所以您只能靠自己了。
请参阅: https ://docs.python.org/2/library/user.html
将此代码放入您的主目录中 ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
将此代码放入您的 main.py(可以在任何地方):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
运行它,你应该得到这个:
$ python main.py
The only way skycake tates good is if.. up in the sky,
the skycookie and sky pie people can't go up and have the sky pie!
SKYCAKE!
如果你在这里得到一个错误: ModuleNotFoundError: No module named 'user'
那么这意味着你正在使用 python3,默认情况下 startuphooks 被禁用。
此 jist 归功于: https ://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py 发送您的上船。
示例 7,最稳健:使用裸导入命令在 Python 中导入文件:
/home/el/foo5/
/home/el/foo5/herp
__init__.py
的空文件: el@apollo:/home/el/foo5/herp$ touch __init__.py
el@apollo:/home/el/foo5/herp$ ls
__init__.py
新建目录 /home/el/foo5/herp/derp
在derp下,制作另一个 __init__.py
文件:
el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
el@apollo:/home/el/foo5/herp/derp$ ls
__init__.py
yolo.py
的新文件 --- 把它放在那里: def skycake():
print "SkyCake evolves to stay just beyond the cognitive reach of " +
"the bulk of men. SKYCAKE!!"
/home/el/foo5/main.py
,把它放在那里; from herp.derp.yolo import skycake
skycake()
el@apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!
空的 __init__.py
文件向 python 解释器传达开发人员希望此目录成为可导入包的信息。
如果您想查看我关于如何在目录下包含所有 .py 文件的帖子,请参见此处: https ://stackoverflow.com/a/20753073/445131
原文由 Eric Leschinski 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
2 回答2k 阅读✓ 已解决
importlib
添加到 Python 3 以编程方式导入模块。应该从
moduleName
中删除 .py 扩展名。该函数还为相对导入定义了一个package
参数。在 python 2.x 中:
import file
没有 .py 扩展名__init__.py
文件__import__
函数,它将模块名称(不带扩展名)作为字符串扩展名键入
help(__import__)
了解更多详细信息。