python知识点结构(五)(5.3接口)5.3.2 sys模块

sys模块

在系统界面进行操作的模块,显示的结果直接在系统界面显示

 1、sys.argv

注意:a)在系统命令界面中输入元素以空格间隔

 1 C:\Python27>python script.py 1,2,3
 2 ['script.py', '1,2,3'] <type 'list'>
 3 Traceback (most recent call last):
 4   File "script.py", line 5, in <module>
 5     j = int(i)
 6 ValueError: invalid literal for int() with base 10: '1,2,3'
 7 
 8 import sys
 9 print sys.argv,type(sys.argv)
10 
11 for i in sys.argv[1:]:
12     j = int(i)
13     print '*'*j
14 
15 C:\Python27>python script.py 1 2 3
16 ['script.py', '1', '2', '3'] <type 'list'>
17 *
18 **
19 ***
20 
21 C:\Python27>
View Code

    b) sys.argv 为列表类型,第一个元素为脚本命。

关于执行: 必须在py的指定的文件夹中执行python 脚本命/py文件名 才能执行。

C:\Users\Administrator>python script.py 1,2,3
python: can't open file 'script.py': [Errno 2] No such file or directory
View Code

怎么能够让py文件在任何路劲下都能执行呢?

在安装python,添加环境变量后,在任何路径输入python后都能显示python的解释器界面。

C:\Users\Administrator>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'aSDA'
>>> a[1:]
'SDA'
>>>
View Code

系统只负责寻找python编译器,要想在任何路径都能执行python文件,就要在python后面加上py文件的绝对路径这样py解释器就能找到py文件了。

C:\Users\Administrator>python C:\Python27\script.py 1 2 3
['C:\\Python27\\script.py', '1', '2', '3'] <type 'list'>
*
**
***

C:\Users\Administrator>
View Code

2、sys.path

在解释器中import一个自建文件/模块

直接在解释器界面sys.path 第一个元素显示'C:/Python27'。

>>> sys.path
['C:/Python27', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']
>>> 
View Code

在cmd界面下启动的python解释器,列表中第一个元素为‘’。

>>> sys.path
['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\
\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27
', 'C:\\Python27\\lib\\site-packages']
>>>
View Code

注意:a)sys.path返回一个列表,所以列表的所有方法都能使用,比如sys.path.append。

  b)列表能容为存放模块路径列表。

  c)只要模块或文件在元素的所示的路径中,就能够正常调用。注意是按照顺序调用,即两个同名不同内容的模块,在不同的路径下,先调用前面的,后面的不会调用。

  d)一般的第三方模块都在'C:\\Python27\\lib\\site-packages'中。

3、sys.exit

4、sys.platform

5、sys.stdout.write

6、sys.stdin.read

posted on 2016-05-31 07:04  lexn  阅读(130)  评论(0)    收藏  举报

导航