2 Python解释器的使用
Table of Contents
- 1 调用解释器
- 1.1 参数传递
- 1.2 交互模式
- 2 解释器及其环境
- 2.1 错误处理
- 2.2 执行Python脚本
- 2.3 源代码编码(Source Code Encoding)
- 2.4 交互式模式的启动文件
- 2.5 定制模块
1
在Linux里,如果安装过python,在shell下键入python即可启动python解释器
- 查看版本 $ python -V Python 2.7.3
- 查看位置 $ which python /usr/bin/python
- 进入交互模式
$ python
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
- 交互模式下编辑方式 Linux下Python交互模式的编辑操作和命令行下的一致,Ctrl+p可以调出键入历史,Ctrl+a行首,Ctrl+e行尾
- 退出交互模式
$ python
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> quit()
$
- 命令行下执行python命令,即用python解释器解释python命令 $ python -c 'print 1' 1
- 命令行下执行python脚本/同时进入交互模式 $ cat foopy.py #! /usr/bin/env python print 1 $ python foopy.py 1 $ python -i foopy.py 1 >>>
1.1
在命令行执行脚本时,脚本名称以及后面的参数会以字符串的形式存储在sys模块的argv数组里:
$ python -i foopy.py hi hello
1
>>> import sys
>>> print sys.argv[0]
foopy.py
>>> print sys.argv[1]
hi
>>> print sys.argv[2]
hello
>>> print sys.argv[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
1.2
前面已经讲过如何进入交互模式,这一节介绍交互模式提示符
- >>> :提示输入命令
>>> print "hello"
hello
- … : 提示输入连续内容
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print "Be carefull not to fall off!"
...
Be carefull not to fall off!
2
2.1
当出现错误时,解释器会打印出错误信息和栈路径,在交互模式下,会返回提示符 >>> 。 在交互模式下键入Ctrl+c会发出一个键盘中断,回到提示符 >>> 。
>>> if the_world_is_flat:
... print "Be"
KeyboardInterrupt #此处是键入 Ctrl+c后出现的
>>> if
KeyboardInterrupt #此处是键入 Ctrl+c后出现的
>>>
2.2
- 首先,python 脚本的首行要有
#! /usr/bin/env python
- 其次,脚本要有执行权限 $ chmod +x foopy.py
- 然后,就可以执行了 $ ./foopy.py 1
2.3
在Python程序的源代码里,可以使用除ASCLL码外的其它编码方式,如果你的python程序中有中文,例如
#! /usr/bin/env python
currency = "你好"
print currency
运行的结果会是:
File "./encodingpy.py", line 4
SyntaxError: Non-ASCII character '\xe4' in file ./encodingpy.py on line 5, but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details
我们只需要加一个声明,指明编码方式即可
#! /usr/bin/env python
# -*- coding: utf-8 -*-
currency = "你好"
print currency
再运行一次:
$ ./encodingpy.py 你好
2.4
在交互式模式下,如果要使用sys模块下的东西,必须先用import导入sys,如果每次启动都要手工导入,就太麻烦了, 另外我们可能需要使用TAB进行补全,这些都需要配置,所以交互模式有一个类似配置文件的东西,在启动交互模式时, 会先执行里面的命令。方法如下:
首先,写一个配置文件 ~/.python.py
import readline
import rlcompleter
readline.parse_and_bind("tab: complete")
然后设置环境变量,在~/.bashrc下添加
export PYTHONSTARTUP=~/.python.py
重新启动shell后,即可在交互模式下使用Tab键来补全
2.5
Python提供了两个hook用于定制Python:sitecustomize 和 usercustomize,首先需要查看site包目录
>>> import site
>>> site.getusersitepackages()
'/home/minix007/.local/lib/python2.7/site-packages'
然后就可以在此目录下创建usercustomize.py文件,文件的内容会影响python的每次调用,除非在调用时使用 -s 选项 禁止自动import。sitecustomize以同样的方式工作,通常由系统管理员定制,它在usercustomize之前被导入。