prompt_toolkit.shortcuts库中的PromptSession()用于创建可定制的命令行提示
The PromptSession class in the prompt_toolkit.shortcuts library is used to create a customizable command line prompt. It provides an interactive interface for fetching user input and displaying prompt messages.
Here's an example that demonstrates the usage of PromptSession():
from prompt_toolkit.shortcuts import PromptSession
from prompt_toolkit.validation import Validator
from prompt_toolkit import print_formatted_text, HTML
# Create a custom validator for input validation
def validate_input(text):
if len(text.strip()) == 0:
raise ValueError("Input cannot be empty!")
return text
# Create a custom message to be displayed before the prompt
message = HTML("<ansired>Enter your name:</ansired> ")
# Create a PromptSession
session = PromptSession()
try:
# Use the PromptSession to display the prompt with the custom message
name = session.prompt(message, validator=Validator.from_callable(validate_input))
# Display the user's input
print_formatted_text(HTML(f"<ansigreen>Hello, {name}!</ansigreen>"))
except KeyboardInterrupt:
print_formatted_text(HTML('<ansired>KeyboardInterrupt received. Exiting...</ansired>'))
In this example, we first import necessary modules such as PromptSession, Validator, and print_formatted_text from the prompt_toolkit library.
Next, we define a custom validator validate_input to validate user input. In this case, we check if the input is empty or not. If it is empty, we raise a ValueError with a respective error message.
Then, we create a custom message message using the HTML class from print_formatted_text module. The message is displayed before the prompt.
After that, we create an instance of PromptSession called session.
Inside a try-except block, we use session.prompt() to display the prompt along with the custom message. We pass validator=Validator.from_callable(validate_input) to validate the user's input with the custom validator we defined earlier. This ensures that the user must enter some value and not just an empty string.
Finally, we display the user's input using print_formatted_text() along with a customized greeting message.
If the user interrupts the program by pressing Ctrl+C (KeyboardInterrupt), the KeyboardInterrupt exception is caught in the except block and an appropriate message is displayed.
This is a basic example of how to use the PromptSession() class from the prompt_toolkit.shortcuts library to create a customizable command line prompt. It allows for various customizations like adding a custom message, validating user input, and displaying formatted text.
