| ???? 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??? |