Files
ailearning/docs/da/064.md
2020-10-19 21:08:55 +08:00

182 lines
2.7 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# sys 模块简介
In [1]:
```py
import sys
```
## 命令行参数
`sys.argv` 显示传入的参数:
In [2]:
```py
%%writefile print_args.py
import sys
print sys.argv
```
```py
Writing print_args.py
```
运行这个程序:
In [3]:
```py
%run print_args.py 1 foo
```
```py
['print_args.py', '1', 'foo']
```
第一个参数 `sys.args[0]` 表示的始终是执行的文件名,然后依次显示传入的参数。
删除刚才生成的文件:
In [4]:
```py
import os
os.remove('print_args.py')
```
## 异常消息
`sys.exc_info()` 可以显示 `Exception` 的信息,返回一个 `(type, value, traceback)` 组成的三元组,可以与 `try/catch` 块一起使用:
In [5]:
```py
try:
x = 1/0
except Exception:
print sys.exc_info()
```
```py
(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('integer division or modulo by zero',), <traceback object at 0x0000000003C6FA08>)
```
`sys.exc_clear()` 用于清除所有的异常消息。
## 标准输入输出流
* sys.stdin
* sys.stdout
* sys.stderr
## 退出Python
`sys.exit(arg=0)` 用于退出 Python。`0` 或者 `None` 表示正常退出,其他值表示异常。
## Python Path
`sys.path` 表示 Python 搜索模块的路径和查找顺序:
In [6]:
```py
sys.path
```
Out[6]:
```py
['',
'C:\\Anaconda\\python27.zip',
'C:\\Anaconda\\DLLs',
'C:\\Anaconda\\lib',
'C:\\Anaconda\\lib\\plat-win',
'C:\\Anaconda\\lib\\lib-tk',
'C:\\Anaconda',
'C:\\Anaconda\\lib\\site-packages',
'C:\\Anaconda\\lib\\site-packages\\Sphinx-1.3.1-py2.7.egg',
'C:\\Anaconda\\lib\\site-packages\\cryptography-0.9.1-py2.7-win-amd64.egg',
'C:\\Anaconda\\lib\\site-packages\\win32',
'C:\\Anaconda\\lib\\site-packages\\win32\\lib',
'C:\\Anaconda\\lib\\site-packages\\Pythonwin',
'C:\\Anaconda\\lib\\site-packages\\setuptools-17.1.1-py2.7.egg',
'C:\\Anaconda\\lib\\site-packages\\IPython\\extensions']
```
在程序中可以修改,添加新的路径。
## 操作系统信息
`sys.platform` 显示当前操作系统信息:
* `Windows: win32`
* `Mac OSX: darwin`
* `Linux: linux2`
In [7]:
```py
sys.platform
```
Out[7]:
```py
'win32'
```
返回 `Windows` 操作系统的版本:
In [8]:
```py
sys.getwindowsversion()
```
Out[8]:
```py
sys.getwindowsversion(major=6, minor=2, build=9200, platform=2, service_pack='')
```
标准库中有 `planform` 模块提供更详细的信息。
## Python 版本信息
In [9]:
```py
sys.version
```
Out[9]:
```py
'2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.1500 64 bit (AMD64)]'
```
In [10]:
```py
sys.version_info
```
Out[10]:
```py
sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0)
```