【问题标题】:Executing a module stored as string values执行存储为字符串值的模块
【发布时间】:2020-06-19 07:38:43
【问题描述】:

我正在调用字符串和随机函数来制作密码生成器。我想确保它尽可能随机,但为此我认为我需要从 string 函数调用 __all__ ,然后从列表中随机选择一个可能的值并然后执行它。

我正在使用 exec 命令从 __any__ 执行一个随机字符串,但我猜 exec 在函数上不起作用,因为它返回 None。对此问题的任何解决方案或解决问题的替代视图都可能会有所帮助。

import random
from  string import *
from string import __all__
while True: #Loop can be ignored, it's just for giving user choice to quit or not. Will add options later
    required_length = input("Enter the length of the password : ") #Length of the password is stored
    letter = __all__ #List containing all the values of string. 
    password = '' #String which will store password
    counter = 1
    while  counter <= int(required_length):
        password = password + str(exec(random.choice(letter))) #Problematic part, the exec statment return None 
        counter += 1
    print (password)

【问题讨论】:

    标签: python python-3.x passwords


    【解决方案1】:

    您可以使用以下代码从所有字符串字符生成密码。

    import random
    from  string import *
    from string import __all__
    while True: #Loop can be ignored, it's just for giving user choice to quit or not. Will add options later
        required_length = input("Enter the length of the password : ") #Length of the password is stored
        letter = "".join([eval(i) for i in __all__ if not callable(eval(i))]) #List containing all the values of string. 
        password = '' #String which will store password
        counter = 1
        while  counter <= int(required_length):
            password = password + str(random.choice(letter)) #Problematic part, the exec statment return None 
            counter += 1
        print (password)
    

    注意:空格字符有问题,不应作为密码的一部分。所以你必须把那部分列入黑名单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      相关资源
      最近更新 更多