您的位置:首页 > 编程语言 > Python开发

python module

2015-11-29 20:25 537 查看
《A Byte Of Python》学习笔记:

一个关键的概念:every python program is also a module.

可以用库调用模块(modules)。 sys module is a bulit-in module of python. the sys.argv variable is a list of strings. the name of the script running is the first argument in the sys.argv list.
Python可以把程序转化成.pyc文件,下一次运行同样的程序时就能直接使用pyc文件,速度更快,且byte-compiled文件时跨平台的。(.pyc文件是和.py文件同路径的)。

os.getcwd()找到当前python文件的路径。
import sys
print('the command line arguments are:')
for i in sys.argv:
print(i)

print ('the pythonpath is')
print (sys.path)

import os
print(os.getcwd())

>>>
the command line arguments are:
H:/51CTO下载-A Byte of Python(for Python 3.0)/practice/module1.py
the pythonpath is
['H:/51CTO\xcf\xc2\xd4\xd8-A Byte of Python\xa3\xa8for Python 3.0\xa3\xa9/practice', 'C:\\Documents and
Settings\\Administrator', 'C:\\Python26\\ArcGIS10.0\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python26.zip',
'C:\\Python26\\ArcGIS10.0\\DLLs', 'C:\\Python26\\ArcGIS10.0\\lib', 'C:\\Python26\\ArcGIS10.0\\lib\\plat-win',
'C:\\Python26\\ArcGIS10.0\\lib\\lib-tk', 'C:\\Python26\\ArcGIS10.0', 'C:\\Python26\\ArcGIS10.0\\lib\\site-pa
ckages', 'C:\\Program Files\\ArcGIS\\Desktop10.0\\bin', 'C:\\Program Files\\ArcGIS\\Desktop10.0\\arcpy',
'C:\\Program Files\\ArcGIS\\Desktop10.0\\ArcToolbox\\Scripts', 'C:\\Program Files\\ArcGIS\\Engine10.0\\bin',
'C:\\Program Files\\ArcGIS\\Engine10.0\\arcpy', 'C:\\Program Files\\ArcGIS\\Engine10.0\\ArcToolbox\\Scripts',
'C:\\Program Files\\ArcGIS\\Server10.0\\bin', 'C:\\Program Files\\ArcGIS\\Server10.0\\arcpy', 'C:\\Program
Files\\ArcGIS\\Server10.0\\ArcToolbox\\Scripts']
H:\51CTO下载-A Byte of Python(for Python 3.0)\practice
>>>

也能用from……import * 语句,它可以一次性的把所有的模块内容加入程序中。但是也可能造成命名冲突。如果只是某些部分高频率使用,可以用 from……import A,B   (加载A,B)
from sys import *
print('the command line arguments are:')
for i in argv:
print(i)

print ('the pythonpath is')
print (path)

>>>
the command line arguments are:
E:/计算机语言/编程文件/python/module 1.py
the pythonpath is
['E:/\xbc\xc6\xcb\xe3\xbb\xfa\xd3\xef\xd1\xd4/\xb1\xe0\xb3\xcc\xce\xc4\xbc\xfe/python', 'D:\\Python27\\Lib\\
idlelib', 'C:\\windows\\SYSTEM32\\python27.zip', 'D:\\Python27\\DLLs', 'D:\\Python27\\lib', 'D:\\Python27\\
lib\\plat-win', 'D:\\Python27\\lib\\lib-tk', 'D:\\Python27', 'D:\\Python27\\lib\\site-packages']
>>>

注:因为是在不同的机器上运行的,所以有不同的结果。

__name__可以用于判断module's name 从而影响程序,创建name__.py文件
if __name__=='__main__':
print 'itself';
else: print 'another module'

>>>
itself
>>> import name__
another module
>>>

当我们把name__.py文件放到和新的.py文件同路径下,新的.py也能import name__
如在mytry.py中写下如下语句:

import name__


运行:
>>>
another module
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: