#!/usr/bin/env python
# Filename: using_sys.py
import sys
print('The command line arguments are:')
for s in sys.argv:
print(s)
print('\n\nThe PYTHONPATH is', sys.path, '\n')
输出:
The command line arguments are:
/home/sy/桌面/python/using_sys.py
The PYTHONPATH is ['/home/sy/桌面/python', '/home/sy', '/usr/bin', '/usr/lib/python3.2', '/usr/lib/python3.2/plat-linux2', '/usr/lib/python3.2/lib-dynload', '/usr/local/lib/python3.2/dist-packages', '/usr/lib/python3/dist-packages']
使用命令行参数:
sy@ubuntu:~/桌面$ cd /home/
sy@ubuntu:/home$ cd ./sy/
sy@ubuntu:~$ cd ./桌面/
sy@ubuntu:~/桌面$ cd ./python/
sy@ubuntu:~/桌面/python$ python3 using_sys.py Hello World.
The command line arguments are:
using_sys.py
Hello
World.
The PYTHONPATH is ['/home/sy/桌面/python', '/usr/lib/python3.2', '/usr/lib/python3.2/plat-linux2', '/usr/lib/python3.2/lib-dynload', '/usr/local/lib/python3.2/dist-packages', '/usr/lib/python3/dist-packages']
sy@ubuntu:~/桌面/python$
换一种方式:
#!/usr/bin/env python
# Filename: using_sys_2.py
from sys import argv
print(argv)
from sys import path
print(path)
打印结果:
['/home/sy/桌面/python/using_sys_2.py']
['/home/sy/桌面/python', '/home/sy', '/usr/bin', '/usr/lib/python3.2', '/usr/lib/python3.2/plat-linux2', '/usr/lib/python3.2/lib-dynload', '/usr/local/lib/python3.2/dist-packages', '/usr/lib/python3/dist-packages']
cat.py
#!/usr/bin/env python
# Filename: cat.py
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = open(filename)
while True:
line = f.readline()
if len(line) == 0:
break
sys.stdout.write(line)
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)
另一个:
#! /usr/bin/env python3.2
# Filename: concatenate.py
import sys
print(sys.version)
print(sys.version_info)
print('concatenate.py')
print()
def readfile(filename):
'''Print a file to the standard output.'''
f = open(filename)
while True:
line = f.readline()
if len(line) == 0:
break
sys.stdout.write(line)
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)
待续