我正在用 elixir 编写 CLI,如何提示用户输入密码,而不在终端中显示输入?
Apparently there are some problems with this. Currently the best solution seems to be to repeatedly clear the input in a loop, as implemented in the Hex package manager:
Just borrow the functionality directly from Mix.Tasks.Hex
, by writing some code like the following,
some_pass =
Mix.Tasks.Hex.password_get("Password: ")
|> String.replace_trailing("\n","")
And if you are requesting the password in a task, and don't want to keep asking for it over and over, you can save it in an environment variable like this,
:os.putenv(String.to_charlist("SECRET_PASSWORD"), String.to_charlist(some_pass))
And, of course, retrieve it with:
System.get_env("SECRET_PASSWORD")
You can accomplish this using the Erlang :io.get_password()
function, eg
IO.write("What is your password?")
password = :io.get_password()
|> List.to_string()
Note that IO.write/1
is preferable to using Mix.shell().info()
for the prompt because the info
function will add a newline, which is usually not what you want in a prompt.
Also be advised that :io.get_password()
returns input as a charlist, so you will probably want to convert it to a binary as demonstrated above.
I wrote a package that utilizes the above technique: https://hex.pm/packages/cowrie
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.