python导入外部文件-如何导入其他Python文件?

导入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$ pythonPython 2.7.3 (default, Sep 26 2013, 20:03:06) >>> import fox>>> fox.what_does_the_fox_say()vixens cry>>>

通过python解释器导入Fox,调用python函数。what_does_the_fox_say()从fox.py。

示例2,使用execfile或(exec在Python 3中)在执行另一个python文件的脚本中:把这个放在/home/el/foo 2/mylib.py中:def moobar():

print("hi")

把这个放在/home/el/foo 2/main.py中:execfile("/home/el/foo2/mylib.py")moobar()

运行文件:el@apollo:/home/el/foo$ python main.py

hi

功能moobar是从mylib.py导入并在main.py中提供的。

例3,使用.进口.。功能:把这个放在/home/el/foo 3/chekov.py中:def question():

print "where are the nuclear wessels?"

把这个放在/home/el/foo 3/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(如果它与导入的文件位置不同)把这个放在/home/el/foo 4/content/riaa.py中:def watchout():

print "computers are transforming into a noose and a yoke for humans"

把这个放在/home/el/foo 4/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导入您的文件:

将此代码放入主目录中~/.pythonrc.pyclass 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.pyThe 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!

示例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/foo 5/herp/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/foo 5/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.pySkyCake evolves to stay just beyond the cognitive reach of the bulk

of men. SKYCAKE!!

空荡荡的__init__.py文件与python解释器通信,开发人员希望这个目录是一个重要的包。