这个功能类似于shell命令行命令后面跟的参数,比如sh test.sh par1 par2 进行命令的执行,对于python有如下类似方法:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
print '*' * 50
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "your first variable is:", first
print "a + b = ",int(second) + int(third)
root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/test# python hardway_exe2.py 1st 50 300
**************************************************
The script is called: hardway_exe2.py
your first variable is: 1st
a + b = 350
这样就可以免去了后续用户的输入,直接一步到位。主要是对argv的调用,另外,参数是以字符串的形式进行读取的,所以用到数字时需要进行类型转换,否则按字符串处理,如下:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
print '*' * 50
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "your first variable is:", first
print "a + b = ",second + third
输出如下,注意等号后的结果,只是把字符串连接起来了
root@loongson-desktop:/home/loongson/lijy-backup/lijy-test/test# python hardway_exe2.py 1st 50 300
**************************************************
The script is called: hardway_exe2.py
your first variable is: 1st
a + b = 50300
这样就避免了使用raw_input进行一个个参数的输入了,还是比较有用的。