| ???? Python ??? | ??14?? Python????? | |
|---|---|---|
| ???? | sys??? | ???? |
sys????????????????????????????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???þŸ??????????§»?????????????????????????????????
??Python???????§Ö??????????????????¡ê???sys.argv?§Ò????????????????????????????????§Ö????????????sys.argv[0]??????Python??0??????????????????????§Ó??????????????
????????????????????????????????§»???????????????????????????????????????????????????????????????????????þŸ????????--version????????·Ú????????????????????????????--help??????????§»???????????????????sys.exit??????????????§Ö????????????????????????help(sys.exit)???????????î•
??????????¦Ê???????????????????????????????????????????????§µ????????????§Ö??????????????????????????
??????¡ê?????cat?? concatenate ????§Õ???????????????????????????????????????????????????????????????????????/?????????????
sys.version????????????????Python??·Ú?????sys.version_info??????????????????????????????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)
?????§à??????????sys????????????????????????sys.stdin??sys.stdout??sys.stderr???????????????????????????????????????
| ???? | ????? | ???? |
|---|---|---|
| ??? | ??? | os??? |