导入 python 文件的方法有很多种,各有优缺点。
不要只是匆忙选择适合您的第一个导入策略,否则当您发现它不能满足您的需求时,您将不得不重写代码库。
我会先解释最简单的例子#1,然后我会转向最专业、最健壮的例子#7
示例1,使用python解释器导入python模块:
-
把这个放在/home/el/foo/fox.py:
def what_does_the_fox_say():
print("vixens cry")
-
进入python解释器:
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 in Python 3) 来执行其他 python 文件:
-
把这个放在/home/el/foo2/mylib.py:
def moobar():
print("hi")
-
把这个放在/home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()
-
运行文件:
el@apollo:/home/el/foo$ python main.py
hi
函数 moobar 从 mylib.py 导入并在 main.py 中可用
示例 3,使用 from ... import ... 功能:
-
把这个放在/home/el/foo3/chekov.py:
def question():
print "where are the nuclear wessels?"
-
把这个放在/home/el/foo3/main.py:
from chekov import question
question()
-
像这样运行它:
el@apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
如果你在 chekov.py 中定义了其他函数,它们将不可用,除非你 import *
示例 4,如果 riaa.py 与导入位置不同,则导入 riaa.py
-
把这个放在/home/el/foo4/stuff/riaa.py:
def watchout():
print "computers are transforming into a noose and a yoke for humans"
-
把这个放在/home/el/foo4/main.py:
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 摆脱了这个用户启动钩子特性集,因为它被低技能的 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,默认情况下启动挂钩在此处禁用。
此 jist 归功于:https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py 发送您的上船。
示例 7,最强大:在 python 中使用裸导入命令导入文件:
- 新建目录
/home/el/foo5/
- 新建目录
/home/el/foo5/herp
-
在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
-
在 /home/el/foo5/herp/derp 下创建一个名为 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