Reputation: 149
I'm trying to create a very simple text editor for an MS-DOS style program I'm making using python. My problem comes when I try to create paragraphs. The way I made it, pressing Enter
tells it to save the input. I understand what I did wrong, but how can I fix it and how could I break the input? So far I have this:
def textwriter():
print("")
print("Start typing to begin.")
textwriterCommand = input(" ")
saveAs = input("Save file as: ")
with open(saveAs, 'w') as f:
f.write(textwriterCommand)
Upvotes: 1
Views: 233
Reputation: 4020
@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
Upvotes: 0
Reputation: 1044
Assign some other EOF sequence, for instance:
EOF_SEQ = 'EOF'
def textwriter():
print("")
print("Start typing to begin.")
buffer = ''
while EOF_SEQ not in buffer:
buffer += raw_input(" ") + '\n'
saveAs = raw_input("Save file as: ")
with open(saveAs, 'w') as f:
f.write(buffer)
Upvotes: 2