【问题标题】:How do I enter a fixed username and password rather than requiring an input field in python?如何在 python 中输入固定的用户名和密码,而不是需要输入字段?
【发布时间】:2020-02-28 22:57:49
【问题描述】:

我有一个 python 脚本,提示输入用户名和密码。这很好,但我想知道我是否可以在文件中预设一个固定的用户名和密码。有什么方法可以轻松地将下面的密码提示编辑为用户名和密码的固定条目? s

    username = input("Enter the username: ")
    password = input("Enter the password: ")

【问题讨论】:

  • 你可以硬编码username = "foo"password = "keepthissecret"。不需要input()。如果它在你的 python 文件中应用,关于它的通常警告真的不是秘密。
  • 用户名 = "David Boykin"
  • 如果这是脚本需要的唯一输入,另一种选择是创建一个文件,前两行是用户名和密码,然后在命令行中输入。 myscript.py < myidentity.txt
  • @tdelaney - 谢谢!这非常有效。

标签: python input passwords


【解决方案1】:

我认为最好的方法听起来像是函数的默认参数。比如:

def log_me_in(username=None, password=None):
    if username is None:
        username = input("Enter the username:\n>>> ")
    if password is None:
        password = input("Enter the password:\n>>> ")
    print("Logging in user {} with password {}".format(username, password))

这使您可以灵活地运行log_me_in("David", "$omething$ecret"),而不必每次都输入这些参数。或者,您可以省略这些参数并使用默认的None 值(强制您在程序执行期间键入输入)。

例子:

log_me_in()

Enter the username:
>>>Dave
Enter the password:
>>>pa$$word
Logging in user Dave with password pa$$word

log_me_in("戴夫")

Enter the password:
>>> My Password
Logging in user Dave with password My Password

log_me_in("Dave", "密码")

Logging in user Dave with password Password

log_me_in(password="A secret")

Enter the username:
>>> Dave
Logging in user Dave with password A secret

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2022-06-25
    • 2016-01-30
    • 1970-01-01
    • 2018-03-27
    相关资源
    最近更新 更多