@zamuz's answer is good, and good for simple things like this, but when your code gets more complex, I prefer to use something like input_constrain, which actually tests each keypress to decide what to do next. (Full disclosure: I wrote this.)
For example, to read input until the user presses |
(vertical bar):
from input_constrain import until
def textwriter():
print("")
print("Start typing to begin.")
textwriterCommand = until("|")
saveAs = input("Save file as: ")
with open(saveAs, 'w') as f:
f.write(textwriterCommand)
Or, to read input until CTRL - C or CTRL - D (or any other unprintable control char):
from input_constrain import until_not
from string import printable as ALLOWED_CHARS
def textwriter():
print("")
print("Start typing to begin.")
textwriterCommand = until_not(ALLOWED_CHARS, count=5000, raw=True)
saveAs = input("Save file as: ")
with open(saveAs, 'w') as f:
f.write(textwriterCommand)
This uses an optional count
parameter, which will stop reading after exactly this many keypresses. raw=True
is important because otherwise, CTRL - C and CTRL - D will throw exceptions. By using raw
, we can break and continue the task at hand.
Important: You need commit 06e4bf3e72e23c9700734769e42d2b7fe029a2c1 because it contains fixes but no breaking changes