陌陌如何伪装地理位置:Python相关[转]

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 19:18:00
http://blog.donews.com/maverick/archive/2007/07/02/1182018.aspx
开发笔记:Python中的Module

Python中的Module是比较重要的概念。常见的情况是,事先写好一个.py文件,在另一个文件中需要import时,将事先写好的.py文件拷贝到当前目录,或者是在sys.path中增加事先写好的.py文件所在的目录,然后import。这样的做法,对于少数文件是可行的,但如果程序数目很多,层级很复杂,就很吃力了。
有没有办法,像Java的Package一样,将多个.py文件组织起来,以便在外部统一调用,和在内部互相调用呢?答案是有的。

要弄明白这个问题,首先要知道,Python在执行import语句时,到底进行了什么操作,按照Python的文档,它执行了如下操作:
第1步,创建一个新的,空的module对象(它可能包含多个module);
第2步,把这个module对象插入sys.module中
第3步,装载module的代码(如果需要,首先必须编译)
第4步,执行新的module中对应的代码。

在执行第3步时,首先要找到module程序所在的位置,其原理为:
如果需要导入的module的名字是m1,则解释器必须找到m1.py,它首先在当前目录查找,然后是在环境变量PYTHONPATH中查找。PYTHONPATH可以视为系统的PATH变量一类的东西,其中包含若干个目录。如果PYTHONPATH没有设定,或者找不到m1.py,则继续搜索与Python的安装设置相关的默认路径,在Unix下,通常是/usr/local/lib/python。
事实上,搜索的顺序是:当前路径(以及从当前目录指定的sys.path),然后是PYTHONPATH,然后是Python的安装设置相关的默认路径。正因为存在这样的顺序,如果当前路径或PYTHONPATH中存在与标准module同样的module,则会覆盖标准module。也就是说,如果当前目录下存在xml.py,那么执行importxml时,导入的是当前目录下的module,而不是系统标准的xml。

了解了这些,我们就可以先构建一个package,以普通module的方式导入,就可以直接访问此package中的各个module了。

Python中的package定义很简单,其层次结构与程序所在目录的层次结构相同,这一点与Java类似,唯一不同的地方在于,Python中的package必须包含一个__init__.py的文件。
例如,我们可以这样组织一个package:

package1/
    __init__.py
    subPack1/
        __init__.py
        module_11.py
        module_12.py
        module_13.py
    subPack2/
        __init__.py
        module_21.py
        module_22.py
    ……

__init__.py可以为空,只要它存在,就表明此目录应被作为一个package处理。当然,__init__.py中也可以设置相应的内容,下文详细介绍。

好了,现在我们在module_11.py中定义一个函数:

def funA():
    print "funcA in module_11"
    return

在顶层目录(也就是package1所在的目录,当然也参考上面的介绍,将package1放在解释器能够搜索到的地方)运行Python:

>>>from package1.subPack1.module_11 import funcA
>>>funcA()
funcA in module_11

这样,我们就按照package的层次关系,正确调用了module_11中的函数。

细心的用户会发现,有时在import语句中会出现通配符*,导入某个module中的所有元素,这是怎么实现的呢?
答案就在__init__.py中。我们在subPack1的__init__.py文件中写

__all__ = ['module_13', 'module_12']

然后进入Python

>>>from package1.subPack1 import *
>>>module_11.funcA()
Traceback (most recent call last):
  File "", line 1, in
ImportError: No module named module_11

也就是说,以*导入时,package内的module是受__init__.py限制的。

好了,最后来看看,如何在package内部互相调用。
如果希望调用同一个package中的module,则直接import即可。也就是说,在module_12.py中,可以直接使用

import module_11

如果不在同一个package中,例如我们希望在module_21.py中调用module_11.py中的FuncA,则应该这样:

from package1.subPack1.module_11 import funcA

当然,在Python 2.5中,有更简单的办法:

from .. subPack1.module_11 import funcA

=======================================================================

http://apps.hi.baidu.com/share/detail/21152508
python os.path模块os和os.path模块
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回但前目录('.')
os.chdir(dirname):改变工作目录到dirname
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径
=======================================================================

PyXDG

PyXDG is a python library to access freedesktop.org standards. Currently supported are:

  • Base Directory Specification Version 0.6
  • Menu Specification Version 1.0
  • Desktop Entry Specification Version 1.0
  • Icon Theme Specification Version 0.8
  • Recent File Spec 0.2
  • Shared-MIME-Database Specification 0.13
http://freedesktop.org/wiki/Software/pyxdg
=======================================================================
http://edu.codepub.com/2010/1104/26953.php
optparse模块OptionParser学习optparse模块OptionParser学习

optparse是专门用来在命令行添加选项的一个模块。
首先来看一段示例代码
from optparse import OptionParser
MSG_USAGE = "myprog[ -f ][-s ] arg1[,arg2..]"
optParser = OptionParser(MSG_USAGE)
optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName")

optParser.add_option("-v","--vison", action="store_false", dest="verbose",default='gggggg',
                     help="make lots of noise [default]")

fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print options.fileName
print options.verbose
print options
print args
print optParser.print_help()
输入结果为
file.txt
False
{'verbose': False, 'fileName': 'file.txt'}
['this is some what', 'arg2', 'arge']
Usage: myprog[ -f ][-s ] arg1[,arg2..]
Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
  -v, --vison           make lots of noise [default]

基本使用步骤
1、 产生一个OptionParser的物件optParse。传入的值MSG_USAGE可被调用打印命令时显示出来。
MSG_USAGE = "myprog[ -f ][-s ] arg1[,arg2..]"
optParser = OptionParser(MSG_USAGE)
2、 调用OptionParser.add_option()添加选项
optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")
optParser.add_option("-v","--vison", action="store_false", dest="verbose",default='gggggg',
                     help="make lots of noise [default]")
add_option()参数说明:
   action:存储方式,分为三种store、store_false、store_true
   type:类型(我也不知道什么的类型)
   dest:存储的变量
   default:默认值
   help:帮助信息
3、 调用OptionParser.parse_args()剖析并返回一个directory和一个list。
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print options.fileName
print options.verbose
print options
print args
输出结果
file.txt
False
{'verbose': False, 'fileName': 'file.txt'}
['this is some what', 'arg2', 'arge']
parse_args()说明:
   如果没有传入参加,parse_args会默认将sys.argv[1:]的值作为默认参数。这里我们将   fakeArgs模拟输入的值。
从返回结果中可以看到,
l     options为是一个directory,它的内容fakeArgs为“参数/值 ”的键值对。
l     args 是一个list,它的内容是fakeargs除去options后,剩余的输入内容。
l     options.version和options.fileName都取到与options中的directory的值。
4、 调用OptionParser.optParser.print_help()输出帮助信息
optParser.print_help() 
   显示返回结果
Usage: myprog[ -f ][-s ] arg1[,arg2..]
Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
  -v, --vison           make lots of noise [default]
optParser.print_help()说明:
1、最开始的的MSG_USAGE的值:在这个地方显示出来了。
2、自动添加了-h这个参数。
     注:在MSG_USAGE中如果使用%prog,会被自动解析为sys.args[0] 也就是文件名。如将,MSG_USAGE = "%prog [options] arg1 arg2",假如文件名为   filexx,那么出现在help中的
信息就是" filexx[options] arg1 arg2"。
深入分析
OptionParser.add_option()
例:optParser.add_option("-v","--vison", action="store_false", dest="verbose",default='gggggg',
                     help="make lots of noise [default]")
参数action:
存储方式,分为三种store、store_false、store_true。
下面分别对三种方式进行说明:
第一种:action = "store"
1、如果输入的参数fakeArgs中存在"-v",则verbose返回的值为fakeArgs中的紧跟'-v'的数,即"good luck to you"。这也正好options中的键值对应,剩下配对的参数都传给了args。请见以下代码
optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")
optParser.add_option("-v","--vison", action="store", dest="verbose")
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print optParse.verbose
print options
print args
输入结果
good luck to you
{'verbose': 'good luck to you', 'fileName': 'file.txt'}
['arg2', 'arge']
2、如果输入的参数fakeArgs中不存在"-v",则verbose的返回值为None。
示例代码:
optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")
optParser.add_option("-v","--vison", action="store", dest="verbose")
fakeArgs = ['-f','file.txt','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print optParse.verbose
print options
print args
输出结果
None
{'verbose': None, 'fileName': 'file.txt'}
['good luck to you', 'arg2', 'arge']
第二种:action = "store_true"
1、fakeArgs中存在'-v',verbose将会返回True而不是"good luck to you"。意思就是说verbose的值与'-v'
的后一位无关,只与'-v'存不存在就关。
示例代码
optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")
optParser.add_option("-v","--vison", action="store_true", dest="verbose")
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print optParse.verbose
print options
print args
输出结果
True
{'verbose': True, 'fileName': 'file.txt'}
['good luck to you', 'arg2', 'arge']
2、fakeArgs中不存在'-v',verbose同样返回空(我就不运行代码了)。
第三种:action="store_false"
这与action="store_true"类似,只有其中有参数'-v'存在,则verbose的值为False,如果'-v'不存在,那么verbose的值为None。
参数:default
optParser.add_option("-v","--vison", action="store_false", dest="verbose",default='gggggg')
设置些参数是用于返回verbose的返回值。
如果action="store",default='gggggg',代码如下。
optParser.add_option("-v","--vison", action="store_false", dest="verbose",default='gggggg')
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
如果fakeArgs中存在'-v',则返回值为,"good luck to you"
如果不存在'-v'则返回值为,"gggggg"
如果action ="store_true",default='gggggg',代码如下。
optParser.add_option("-v","--vison", action="store_true", dest="verbose",default='gggggg')
如果fakeArgs中存在'-v',则返回值为True。
如果fakeArgs中不存在'-v',则返回值为None
再一次说明了,如果action="store_true"时,verbose的值只与是否'-v'有关。是否也说明了action_true的优先级高于default。
注:action="store_false"的功能与此类似,返回为False或者None。再一次证明了
参数:help
optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")
optParser.add_option("-v","--vison", action="store", dest="verbose",default='gggggg',
                     help="make lots of noise [default]")
主要用于显示帮助信息,使用optParser.print_help()将帮助栏显示出来。
在action="restore"时对比没使用help参数的'-f'与使用了help参数的'-v',多了一行帮助信息。
Usage: myprog[ -f ][-s ] arg1[,arg2..]
Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
  -v VERBOSE, --vison=VERBOSE
                        make lots of noise [default]
在action="restore_false"时。
optParser.add_option("-f","--file",action = "store",type = "string",dest = "fileName")
optParser.add_option("-v","--vison", action="store", dest="verbose",default='gggggg',
                     help="make lots of noise [default]")

两个对比的输出结果如下
Usage: myprog[ -f ][-s ] arg1[,arg2..]

Options:
  -h, --help            show this help message and exit
  -f FILENAME, --file=FILENAME
  -v, --vison           make lots of noise [default]
参数:type
  没有仔细测试,但知道一点时如果type="string"时,将无法使用action="store_false"和action="store_true"。不知是否可以将type理解成verbose的返回值类型。
关于输入的的参数fakeArgs的说明
还是用之前的代码分析
from optparse import OptionParser

MSG_USAGE = "myprog[ -f ][-s ] arg1[,arg2..]"
optParser = OptionParser(MSG_USAGE)
optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName")
optParser.add_option("-v","--vison", action="store", dest="verbose",default='gggggg',
                     help="make lots of noise [default]")
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print options
print args
fakeArgs中的值对于各选项'-v','-f'来说都是前后两个值配对的。
1、正常情况:
结果如下
则options的值为:     {'verbose':'good luck to you', 'fileName': 'file.txt'}
args的值为:           ['arg2', 'arge']
2、不正常情况:
如果连续出现两个选项'-f','-v'。
fakeArgs = ['-f','-v','good luck to you', 'arg2', 'arge']
'-v'作为值传给了fileName。
但verbose返回的是默认值'gggggg',如果没设置将会返回None。换句说话,就是没检测到参数'-v'的存在,这也再一次说明了,fakeArgs中键值配对的观念。前一个数作为选项,后一个作为值。
结果如下:
则options的值为:     {'verbose':'gggggg', 'fileName': '-v'}
args的值为:           ['good luck to you','arg2', 'arge']
3、如果多出一个'x'未被定义则程序会报错。
fakeArgs = ['-x','-f','file.txt','-v','good luck to you', 'arg2', 'arge']
========================================================================================
字符串直接用+连接效率很低,如何是大量循环,用'%s %s' % ('xxx','yyy')
========================================================================================
Aptdaemon allows normal users to perform packagemanagement tasks, e.g. refreshing the cache, upgrading the system,installing or removing software packages.

Currently it comes with the following main features:
- Programming language independent D-Bus interface, which allows to write clients in several languages
- Transaction based design which allows to queue actions
- The daemon runs only if required (D-Bus activation)
- Fine grained privilege management using PolicyKit, e.g. allowing alldesktop user to query for updates without entering a password
- Support for media changes during installation from DVD/CDROM
- Support for debconf (Debian's package configuration system)
- Support for attaching a terminal to the underlying dpkg call
- Command line client aptdcon
- Python GTK widgets to monitor and control a running transaction

Aptdaemon was inspired by PackageKit which doesn't allow a tightintegration into Debian/Ubuntu by policy: Running transaction are notallowed to be paused. This makes the use of debconf or resolving configfile conflicts impossible.

The documentation can be found at the home page.

DBus driven daemon for APT

Aptdaemon allows to perform package management tasks in a background processcontrolled by DBus. It is greatly inspired by PackageKit, which doesn't supportessential features of apt by policy.

http://pypi.python.org/pypi/aptdaemon/0.40

========================================================================================

What is D-Bus?

D-Bus is amessage bus system, a simple way for applications to talk to oneanother. In addition to interprocess communication, D-Bus helpscoordinate process lifecycle; it makes it simple and reliable to code a"single instance" application or daemon, and to launch applications anddaemons on demand when their services are needed.

D-Bussupplies both a system daemon (for events such as "new hardware deviceadded" or "printer queue changed") and a per-user-login-session daemon(for general IPC needs among user applications). Also, the message busis built on top of a general one-to-one message passing framework, whichcan be used by any two apps to communicate directly (without goingthrough the message bus daemon). Currently the communicatingapplications are on one computer, or through unencrypted TCP/IP suitablefor use behind a firewall with shared NFS home directories. (Helpwanted with better remote transports - the transport mechanism is well-abstracted and extensible.)

The D-Bus low-level API reference implementation and protocolhave been heavily tested in the real world over several years, and arenow "set in stone." Future changes will either be compatible orversioned appropriately.

Thelow-level libdbus reference implementation has no requireddependencies; the bus daemon's only *required* dependency is an XMLparser (either libxml or expat). Higher-level bindings specific toparticular frameworks (Qt, GLib, Java, C#, Python, etc.) add moredependencies, but can make more assumptions and are thus much simpler touse. The bindings evolve separately from the low-level libdbus, so someare more mature and ABI-stable than others; check the docs for thebinding you plan to use.

Thereare also some reimplementations of the D-Bus protocol for languagessuch as C#, Java, and Ruby. These do not use the libdbus referenceimplementation.

Itshould be noted that the low-level implementation is not primarilydesigned for application authors to use. Rather, it is a basis forbinding authors and a reference for reimplementations. If you are ableto do so it is recommended that you use one of the higher level bindingsor implementations. A list of these can be found on the bindings page.
http://www.freedesktop.org/wiki/Software/dbus
========================================================================================
Python中的Signal/Slot机制与Qt的差异()
Signals and slots come in two basicvarieties: Vanilla, or C++ signals and slots (as defined in theQt library) and Pythonic (signals and slots defined in Python).Any function of any object can be used as a slot in Python (youdon't even have to inherit from QObject).This contrasts to C++, where you need to specially mark afunction as a slot in order to be able to connect it to a signal(and have to inherit QObject).

Note that we connect the C++ signals(SIGNAL), to Python functions. You simply give the functionobject as the slot argument— not the result of thefunction call.

Python signals are indicated by thePYSIGNAL() function, which also takes astring. There is no PYSLOT() functioncorresponding to SLOT(), because you canuse any function as a slot inPython.

The argument of PYSIGNAL() is a simplestring that is unique for the class from which the signal isemitted. It performs the same function as theoccasion string in the smallregistry.py script. The difference is thatPYSIGNAL() string needs to be unique onlyfor the class, and not the whole application.


Table 7-1. Matrix ofQObject.connect()combinations.

Table 7-1. Matrix ofQObject.connect()combinations.

Signal Connected to Syntax (Note that you can replace QObject.connect() by self.connect() everywhere.) C++ C++ slot of another object QObject.connect(object1, SIGNAL("qtSignal()"), object2, SLOT("qtSlot()")) C++ C++ slot of 'self' object QObject.connect(object1, SIGNAL("qtSignal()"), SLOT("qtSlot()")) C++ Python slot of another object QObject.connect(object1, SIGNAL("qtSignal()"), object2, pythonFunction) C++ Python slot of 'self' object QObject.connect(object1, SIGNAL("qtSignal()"), self.pythonFunction) C++ C++ signal of another object QObject.connect(object1, SIGNAL("qtSignal()"), object2, SIGNAL("qtSignal()") C++ C++ signal of 'self' object QObject.connect(object1, SIGNAL("qtSignal()"), self, SIGNAL("qtSignal()") Python C++ slot of another object QObject.connect(object1, PYSIGNAL("pySignal()"), object2, SLOT("qtSlot()")) Python C++ slot of 'self' object QObject.connect(object1, PYSIGNAL("pySignal()"), SLOT("qtSlot()")) Python Python slot of another object QObject.connect(object1, PYSIGNAL("pySignal()"), object2.pythonFunction)) Python Python slot of 'self' object QObject.connect(object1, PYTHON("pySignal()"), self.pythonFunction)) Python C++ signal of another object QObject.connect(object1, OYSIGNAL("pySignal()"), object2, SIGNAL("qtSignal()") Python C++ signal of 'self' object QObject.connect(object1, PYSIGNAL("pySignal()"), self, SIGNAL("qtSignal()") Python Python signal of another object QObject.connect(object1, PYSIGNAL("pySignal()"), object2, PYSIGNAL("pySignal()") Python Python signal of 'self' object QObject.connect(object1, PYSIGNAL("pySignal()"), PYSIGNAL("pySignal()") ========================================================================================

python pass

pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作,比如:

while False:

pass

pass通常用来创建一个最简单的类:

class MyEmptyClass:

pass

pass在软件设计阶段也经常用来作为TODO,提醒实现相应的实现,比如:

def initlog(*args):

pass #please implement this

http://www.cppblog.com/momoxiao/archive/2010/08/23/124425.aspx?opt=admin
========================================================================================

http://apt.alioth.debian.org/python-apt-doc/library/index.html

Python APT’s library provides access to almost every functionality supportedby the underlying apt-pkg and apt-inst libraries. This means that it ispossible to rewrite frontend programs like apt-cdrom in Python, and this isrelatively easy, as can be seen in e.g. Writing your own apt-cdrom.

When going through the library, the first two modules are apt_pkg andapt_inst. These modules are more or less straight bindings to theapt-pkg and apt-inst libraries and the base for the rest of python-apt.

Going forward, the apt package appears. This package is usingapt_pkg and :mod`apt_inst` to provide easy to use ways to manipulatethe cache, fetch packages, or install new packages. It also provides usefulprogress classes, for text and GTK+ interfaces. The last package isaptsources. The aptsources package provides classes and functions toread files like /etc/apt/sources.list and to modify them.

lass apt.cache.Cache(progress=None, rootdir=None, memonly=False)

Dictionary-like package cache.

This class has all the packages that are available in it’sdictionary.

Keyword arguments:progress – a OpProgress objectrootdir – a alternative root directory. if that is given

the system sources.list and system lists/ files arenot read, only files relative to the given rootdir

memonly – build the cache in memory only

cache[pkgname]

Return a Package() for the package with the name pkgname.

========================================================================================

========================================================================================

========================================================================================

========================================================================================

========================================================================================

========================================================================================