命令行参数
加密程序
考虑这样一个加密程序,其中一个功能,是对一段字符串进行base64加密,另一个功能,是对一段base64字符串解密:
import base64
def encrypt_to_base64(input_string):
byte_data = input_string.encode("utf-8")
base64_encoded = base64.b64encode(byte_data)
return base64_encoded.decode("utf-8")
def decrypt_from_base64(base64_string):
byte_data = base64_string.encode("utf-8")
decoded_data = base64.b64decode(byte_data)
return decoded_data.decode("utf-8")
encrypt_to_base64("sagegrass")
decrypt_from_base64("c2FnZWdyYXNz")
对于这样一个功能,如果我希望通过命令行调用,然后快速得到结果,可能是像这样的:
# 设置-e选项,进行加密
python base64_encrypt.py -e "sagegrass"
# 设置-d选项,进行解密
python base64_encrypt.py -d "c2FnZWdyYXNz"
那么,该怎么做到呢?
sys.argv
命令行参数以列表的形式,保存于sys模块的argv属性中,具体来说
import sys
print(sys.argv)
# 对于python base64_encrypt.py -e "123456",结果为:['base64_encrypt.py', '-e', 'sagegrass']
# 对于python base64_encrypt.py -d "MTIzNDU2",结果为:['base64_encrypt.py', '-d', 'c2FnZWdyYXNz']
处理命令行参数
因此,根据sys.argv的返回结果,我们可以假设,如果用户的使用方法正确,那么,我们可以:
import base64
import sys
def encrypt_to_base64(input_string):
byte_data = input_string.encode("utf-8")
base64_encoded = base64.b64encode(byte_data)
return base64_encoded.decode("utf-8")
def decrypt_from_base64(base64_string):
byte_data = base64_string.encode("utf-8")
decoded_data = base64.b64decode(byte_dat