Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module,definitions from a module can be imported into other modules or into the main module
Python提供了一种可以从文件中定义然后在一个脚本或交互实例中使用的方法,而这个文件我们称之为模块,模块中的定义可以导入到另一个模块或者主模块之中
模块导入:这里为了方便说明,我们假设有mymodule.py和test.py两个模块,需要在test.py中使用mymodule.py定义的函数或者变量。
1,简单定义一个mymodule.py,
# Filename:mymodule.py
'''this is a simple module
module is very easy to learn'''
def Say():
print 'this is mymodule speaking'
version = '0.1'
time = '2012-12-13'
这里保存在"D:\Pydata"里面,然后ctrl + R 输入cmd,打开命令行提示符,输入python,进入python环境(如果为出现,请设置环境变量,环境变量的设置是……这是另外一个话题了,请自行百度),ok,在输入python后我们看到如下界面:
2.依次输入import sys-->sys.path,得到如下界面:
为了要使用我之前创建的mymodule.py里面的函数,我们需要把“D:\Pydata”添加到sys的路径下面去。
此时我们可以输入sys.path.append('D:\\Pydata'),注意哦,这个地方是双斜杠。
3.再次输入sys.path:
这样我们就将存放module的目录D:\Pydata放入了系统搜索路径下去了。
最后,我们就可以输入import mymodule-->mymodule.sayhi()以及mymodule.version
分别返回值是:“hi,this is my module specking"和“0.1”.
到这里我们就学会了在python命令行里面使用我们自己定义的module的方法了。但是关于module在程序里面我们还有
地方需要学习的,比如同一个文件夹之间相互的调用已经不文件夹下两个module之间的相互调用问题