plantegg 发表于 2015-4-24 09:21:27

熟悉Python Interpreter解释器


  1. 启动python解释器
  2. python解释器的两种模式
  3. 错误处理
  4. 设置python解释器启动代码
  5. 执行python module
  5.1 python文件注释
  5.2 如何编写中文注释
  5.3 如何执行.py文件
. 启动python解释器;
  上一篇中,我们安装了python,并且在eclipse下安装了pydev插件,并且熟悉了这个ide的开发环境,这里我们将看看如何在命令行下玩一下python(windows环境下)。第一步我们来启动该解释器,在windows下如果设置了环境变量的话,直接在cmd下键入python即可,或者是cd到python的安装目录下,执行./python.exe。
. python解释器的两种模式;
  按照上一步启动python的解释器之后,默认的将进入Interactive Mode交互模式,解释器将在等待用户输入。python解释器允许将一个“命令”在多行书写,此时python解释器将使用...提示用户,如下:


D:\pythonwork>python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> the_word_is_flat = 1;
>>> if the_word_is_flat :
...   print("be careful not to fail off");
...
be careful not to fail off  >>>
. 错误处理;
  如果解释器在解析命令时出现错误,那么Interpreter将打印error message和a stack trace,和其他语言类似,在python中也存在错误处理,这将在后面介绍。
.python解释器启动代码

The Interactive Startup File;
  python解释器可以设置启动时运行的命令,可以通过设置环境变量PYTHONSTARTUP来实现,如下:

  Starup.py文件:
  print("python Interpreter is going to start !");
  这时,重新启动python解释器时结果:
  D:\pythonwork>python


Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) on
win32
Type "help", "copyright", "credits" or "license" for more information.
python Interpreter is going to start !
>>>. 执行一个python module;
  5.1 python文件注释
  python文件中可以使用两种类型的注释,如果是单行注释,可以使用#号:


# this is a comment  a = 10;
  如果是多行注释的话,可以使用''':


'''
python tourial :
    An Informal Introduction to Python  '''
  5.2 如何支持中文注释
  可以通过设置.py文件的编码方式来支持中文注释:


# -*- coding: utf-8 -*-
# 需要加上上面一句表明该文件编码方
# 式,否则在命令行下执行报错
import sys;  print(sys.argv);
  5.3 执行一个.py文件
  如果已经编写完成了一个.py文件,那么可以通过如下命令执行,python + .py文件名:
  D:\pythonwork>python Startup.py
  同时可以向该文件中传递参数:
  D:\pythonwork>python Startup.py"arg1"


python Interpreter is going to start !  向该文件传递的参数可以通过sys.argv来得到:
  # -*- coding: utf-8 -*-


'''
打印命令行参数
'''
import sys;

print(sys.argv);
页: [1]
查看完整版本: 熟悉Python Interpreter解释器