Sto cercando di ottenere il comportamento dei client IM tipici che utilizzano Return
per inviare un testo e Shift + Return
per inserire un'interruzione di riga. C'è un modo per ottenerlo con il minimo sforzo in Python, usando per es. readline e raw_input
?Maiusc + Invio per inserire interruzione di riga in python
risposta
Ok, ho sentito che può essere realizzato anche con il readline
, in un certo senso.
È possibile import readline
e impostare nella configurazione il tasto desiderato (Maiusc + Invio) in una macro che inserisce un carattere speciale alla fine della riga e di nuova riga. Quindi è possibile chiamare raw_input
in un ciclo.
Ti piace questa:
import readline
# I am using Ctrl+K to insert line break
# (dont know what symbol is for shift+enter)
readline.parse_and_bind('C-k: "#\n"')
text = []
line = "#"
while line and line[-1]=='#':
line = raw_input("> ")
if line.endswith("#"):
text.append(line[:-1])
else:
text.append(line)
# all lines are in "text" list variable
print "\n".join(text)
Dubito che saresti in grado di farlo usando il modulo readline
in quanto non catturerà i singoli tasti premuti e piuttosto elaborerà solo le risposte dei caratteri dal tuo driver di input.
si potrebbe fare con PyHook anche se e se la chiave Shift
viene premuto insieme alla chiave Enter
per iniettare una nuova linea nella vostra readline
flusso.
Grazie, ma mi piacerebbe mantenere la compatibilità della piattaforma con * nix! –
Penso che con il minimo sforzo è possibile utilizzare la libreria urwid per Python. Sfortunatamente, questo non soddisfa il tuo requisito di usare readline/raw_input.
Aggiornamento: Vedere anche this answer per altra soluzione.
import readline
# I am using Ctrl+x to insert line break
# (dont know the symbols and bindings for meta-key or shift-key,
# let alone 4 shift+enter)
def startup_hook():
readline.insert_text('» ') # \033[32m»\033[0m
def prmpt():
try:
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')
readline.parse_and_bind('C-x: "\x16\n"') # \x16 is C-v which writes
readline.set_startup_hook(startup_hook) # the \n without returning
except Exception as e: # thus no need 4 appending
print (e) # '#' 2 write multilines
return # simply use ctrl-x or other some other bind
while True: # instead of shift + enter
try:
line = raw_input()
print '%s' % line
except EOFError:
print 'EOF signaled, exiting...'
break
# It can probably be improved more to use meta+key or maybe even shift enter
# Anyways sry 4 any errors I probably may have made.. first time answering
Siete alla ricerca di piattaforma di risposta dipendente o indipendente? – Jiri
Piattaforma indipendente se possibile, ma * nix compatibile dovrebbe fare come l'applicazione si rivolge comunque agli utenti della riga di comando. –