Python自帶常量(本例中改用這個,不用手工定義了) string.digits #十進制數字:0123456789 string.octdigits #八進制數字:01234567 string.hexdigits #十六進制數字:0123456789abcdefABCDEF string.ascii_lowercase #小寫字母(ASCII):abcdefghijklmnopqrstuvwxyz string.ascii_uppercase #大寫字母(ASCII):ABCDEFGHIJKLMNOPQRSTUVWXYZ string.ascii_letters #字母:(ASCII)abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ string.punctuation #標點符號:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
#!/usr/bin/python #coding=utf8 from random import choice import string,sys passwd_seed = string.digits + string.ascii_lowercase + string.ascii_letters + string .punctuation """function to generate a passwd""" def get_passwd(passwd_length=10): ####默認值 passwd = [] while len(passwd) < passwd_length: passwd.append(choice(passwd_seed)) password=''.join(passwd) #password=password.replace("'","\\\'")###這裏是爲了轉義引號,在傳入md5加密時遇到引號不識別 #password=password.replace('"','\\\"')### return password if __name__ == "__main__": if len(sys.argv) == 1: print get_passwd() else: length = int(sys.argv[1]) print get_passwd(length)