使用 random 模块的样本函数时出现 EOF 错误

问题描述 投票:0回答:1

我正在使用 python 创建一个简单的密码生成器应用程序,因为我是随机模块的新手,所以我使用了它的带有字符和长度序列的sample()函数。但它向我显示这个 EOF 错误为

Traceback (most recent call last):
  File "./prog.py", line 2, in <module>
EOFError: EOF when reading a line 

这是我的代码

from random import *    
length=int(input("What should be the length of Password:   "))
sequence='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&/\|?<>*'
password=''
mylist=sample(sequence,length)
for i in mylist:
    password+=str(i)
print(password)

然后我尝试使用 try 和 except 逻辑

from random import sample

try:
    # Prompt the user to specify the desired length of the password
    length = int(input("What should be the length of the password: "))
    
    if length <= 0:
        print("Please enter a positive integer for the password length.")
    else:
        # Define the sequence of characters to choose from
        sequence = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&/\|?<>*'
        
        # Generate the password
        password = ''.join(sample(sequence, length))
        
        # Display the generated password
        print("Generated password:", password)
except ValueError:
    print("Invalid input. Please enter a valid number.")
except EOFError:
    print("Input error. Unable to read input.")

我期待这可能会给我一个指定长度的随机字符序列,可以用作密码。

python random
1个回答
0
投票

似乎工作正常,尝试过在线编译器 enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.