���� Python �̳�
��14�� Python��׼��
��һҳ sysģ�� ��һҳ

sys�

sysģ�����ϵͳ��Ӧ�Ĺ��ܡ������Ѿ�ѧϰ��sys.argv�б��������������в�����

�������

��14.1 ʹ��sys.argv

#!/usr/bin/python
# Filename: cat.py


import sys

def readfile(filename):
    '''Print a file to the standard output.'''
    f = file(filename)
    while True:
        line = f.readline()

        if len(line) == 0:
            break
        print line, # notice comma
    f.close()

# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
    sys.exit()

if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':
        print 'Version 1.2'
    elif option == 'help':
        print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
  --version : Prints the version number
  --help    : Display this help'''

    else:
        print 'Unknown option.'
    sys.exit()
else:
    for filename in sys.argv[1:]:
        readfile(filename)

��Դ�ļ���code/cat.py��

���

$ python cat.py
No action specified.

$ python cat.py --help
This program prints files to the standard output.
Any number of files can be specified.
Options include:
  --version : Prints the version number
  --help    : Display this help

$ python cat.py --version
Version 1.2

$ python cat.py --nonsense
Unknown option.

$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!

������

�����������ģ��Linux/Unix�û���Ϥ��cat�����ֻ��Ҫָ��ijЩ�ı��ļ������֣�������������Ǵ�ӡ�����

��Python�������е�ʱ�򣬼������ڽ���ģʽ�£���sys.argv�б�������������һ����Ŀ�������ǵ�ǰ���еij������ƣ���Ϊsys.argv[0]������Python��0��ʼ�������������������в����������Ŀ֮��

Ϊ��ʹ���������û������Ѻã������ṩ��һЩ�û�����ָ����ѡ�����˽�����������ݡ�����ʹ�õ�һ���������������ǵij����Ƿ�ָ����ѡ����ʹ����--versionѡ�����İ汾�Ž�����ӡ���������Ƶأ����ָ����--helpѡ������ṩһЩ���ڳ���Ľ��͡�����ʹ��sys.exit�����˳��������еij��򡣺�����һ��������Կ�һ��help(sys.exit)���˽�������顣

���û��ָ���κ�ѡ�����Ϊ�����ṩ�ļ����Ļ������ͼ򵥵ش�ӡ��ÿ���ļ���ÿһ�У������������е�˳��һ���ļ�����һ���ļ��ش�ӡ��

˳��˵һ�£�����cat�� concatenate ����д���������ϱ����˳���Ĺ��ܡ����������������ӡһ���ļ����߰����������������ļ�����/������һ���ӡ��

����sys������

sys.version�ַ��������ṩ��װ��Python�İ汾��Ϣ��sys.version_infoԪ�����ṩһ�����򵥵ķ�����ʹ��ij���߱�Python�汾Ҫ���ܡ�

[swaroop@localhost code]$ python
>>> import sys
>>> sys.version
'2.3.4 (#1, Oct 26 2004, 16:42:40) \n[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)]'
>>> sys.version_info
(2, 3, 4, 'final', 0)

�����о���ij���Ա��sysģ�����������˸���Ȥ����Ŀ��sys.stdin��sys.stdout��sys.stderr���Ƿֱ��Ӧ��ij���ı�׼���롢��׼����ͱ�׼��������


��һҳ ��һ�� ��һҳ
��� ��ҳ osģ��