原文地址:http://stackoverflow.com/questions/2349991/python-how-to-import-other-python-files/20749411#20749411

There are many ways to import a python file, all with their pros and cons.

Don’t just hastily pick the first import strategy that works for you or else you’ll have to rewrite the codebase later on when you find it doesn’t meet your needs.

I’ll start out explaining the easiest example #1, then I’ll move toward the most professional and robust example #5

Example 1, Import a python module with python interpreter:

Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
print(“vixens cry”)
Get into the python interpreter:

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

You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.
Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

Put this in /home/el/foo2/mylib.py:
def moobar():
print(“hi”)
Put this in /home/el/foo2/main.py:
execfile(“/home/el/foo2/mylib.py”)
moobar()
run the file:

el@apollo:/home/el/foo$ python main.py
hi
The function moobar was imported from mylib.py and made available in main.py
Example 3, Use from … import … functionality:

Put this in /home/el/foo3/chekov.py:
def question():
print “where are the nuclear wessels?”
Put this in /home/el/foo3/main.py:
from chekov import question
question()
Run it like this:

el@apollo:/home/el/foo3$ python main.py
where are the nuclear wessels?
If you defined other functions in chekov.py, they would not be available unless you import *
Example 4, Import riaa.py if it’s in a different file location from where it is imported

Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
print “my message”
Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath(“/home/el/foo4/stuff”))
from riaa import *

watchout()
Run it:

el@apollo:/home/el/foo4$ python main.py
my message
That imports everything in the foreign file from a different directory.
Example 5, Import files in python with the bare import command:

Make a new directory /home/el/foo5/
Make a new directory /home/el/foo5/herp
Make an empty file named init.py under herp:
el@apollo:/home/el/foo5/herp$ touch init.py
el@apollo:/home/el/foo5/herp$ ls
init.py
Make a new directory /home/el/foo5/herp/derp
Under derp, make another init.py file:
el@apollo:/home/el/foo5/herp/derp$ touch init.py
el@apollo:/home/el/foo5/herp/derp$ ls
init.py
Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
print “SkyCake evolves to stay just beyond the cognitive reach of ” +
“the bulk of men. SKYCAKE!!”
The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()
Run it:

el@apollo:/home/el/foo5$ python main.py
SkyCake evolves to stay just beyond the cognitive reach of the bulk
of men. SKYCAKE!!
The empty init.py file communicates to the python interpreter that the developer intends this directory to be an importable package.
If you want to see my post on how to include ALL .py files under a directory see here: http://stackoverflow.com/a/20753073/445131

Example 6, use os.system(“python yourfile.py”)

import os
os.system(“python yourfile.py”)
Bonus protip

whether you are using Mac, Linux or Windows, you need to be using python’s idle editor as described here. It will unlock your python world. http://www.youtube.com/watch?v=DkW5CSZ_VII

Python: How to import other Python files相关推荐

  1. python哪里下载import包-python import 自己的包

    在写python时,有时候写的一个python文件可能需要被其他python文件所用,那么可以用导入包 import 的 方式: 1.自己写的包放到哪里? >>> import sy ...

  2. python哪里下载import包-python 如何找到import的包

    Python import 时会首先寻找 sys.path 中列出的路径,通常是这样: >>> import sys >>> ' '.join(sys.path) ...

  3. java可以使用python的库函数_java调用python方法总结

    一.在java类中直接执行python语句 import org.python.util.PythonInterpreter; public class FirstJavaScript { publi ...

  4. java调用python项目实战_Java调用Python

    今天遇到Java调用一个Python脚本的问题,纠结了大半天,遇到各种问题.网上搜索的大部分都是用jython,但是我想要调用的python脚本里有import urllib,这个urllib也不是什 ...

  5. java运行python脚本_java中执行python脚本工具类详解

    java中执行python脚本工具类,需要jython.jar import java.io.FileInputStream; import java.io.IOException; import j ...

  6. 【Python知识点梳理】10.Python的垃圾回收机制、代码规范及命令行参数

    Python的垃圾回收机制.代码规范及命令行参数 文章目录 1.Python的垃圾回收机制 2.Python的引用计数机制 3.Python中的循环数据结构及引用计数 4.Python中的GC模块 5 ...

  7. 【Python】创建Vue项目报错python.EXE -c import sys; print “%s.%s.%s“ % sys.version_info[:3];

    1.错误情况 gyp verb `which` succeeded python C:\Users\Software\Python\Python310\python.EXE gyp ERR! conf ...

  8. python 第三方包自动导入_7行代码,彻底告别python第三方包import导入问题!

    最近有不少小伙伴咨询关于pyton第三方包导入的问题,今天我们就来聊聊第三方包导入那些事. 随着对python学习的渐入臻境,越来越多的小伙伴们开始导入自己所需的第三方包,实现各种各样的功能.但是,他 ...

  9. python安装modify setup选哪-python 之禅 import this

    dongweiming的博客 前言 我这个博客一直都是一些技术分享,show code的地方,我从来没有写过个人生活或者情感杂谈,当然我也从来没有谈论过我对什么东西的喜恶. 很多人喜欢喷XX语言,喜欢 ...

最新文章

  1. linux parted rpm,为Everest Linux构建QtParted的rpm包(四)
  2. 随笔分类 - java高级特性
  3. C#中三种截屏方式总结
  4. Active Directory 定义了五种操作主机角色
  5. [Android] TextView 分页功能的实现
  6. nodejs安装失败
  7. Retrofit使用
  8. 通过Python实现九九乘法表
  9. 上海计算机三级怎么查,2013上海计算机三级成绩查询系统
  10. ACM/ICPC 2018亚洲区预选赛北京赛站网络赛 B. Tomb Raider(二进制枚举)
  11. Fluent UDF代码编写
  12. linux 计算程序运行时间
  13. nagiso中nsca的配置
  14. Elasticsearch基于地理位置查询 geo_point
  15. Python 通过邮件自更新
  16. 传统算法与神经网络算法,神经网络是机器算法吗
  17. 批量删除word中的分隔符
  18. Windows XP 进程分类(必要,需要,不要)windows xp 必要进程
  19. MinIO API responded with message=Please reduce your request
  20. 手把手教你绩效管理体系-OKR

热门文章

  1. Linux下FTP服务器搭建
  2. 的电路接法_放大电路的三种基本接法分享
  3. 弹出窗口显示输出内容_前端加油站(3)-JavaScript 输出
  4. 处理报错:java/lang/NoClassDefFoundError: java/lang/Object
  5. spring boot创建多模块聚合工程
  6. JDK8中ConcurrentHashMap源码解析
  7. sublime Text3 设置多个浏览器预览
  8. 苹果开始整治App Store恶意抄袭现象
  9. PMWiki安装教程
  10. 单片机里XPL是什么_单片机可以替代PLC么?