python module

《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
>>> 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值