How to do after user use input not break line

Asked

Viewed 1,286 times

2

Turns out I want to use an input, ie put a value but after hitting enter not break the line but continue in the place where I wrote the value, I have no idea how to do with the python input, I tried to do this:

a = input("", end="")

but makes the following mistake

"input() takes no keyword arguments".

Well the code I’m thinking of doing is about putting the date in DD/MM/YYYY format.
Only every time you use input() you hit enter when you put the value, type 20, the cursor goes to the bottom line to write something else if you put another input, but I want it to continue on the same line as I put the date 20, for then I by a / to appear and then put 05 of the month for example.

Well that’s it, thank you!

  • Could edit the question and put the code ?

  • I edited the question.

  • You want the enter that the user gives to put the input does not break the line is this ? If so, I don’t think it’s possible, at least on console.

  • That’s right, well then it seems I should delete the question. But thank you very much.

  • The ideal will be to wait for the feedback of other people in the community. Maybe someone knows a way around, or maybe they confirm what I said.

  • Okay, I’ll wait, is that in another language this is possible?

  • Hello @Lucasfariasrodrigues as is? I hope you like Stack Overflow. For your answer, you can use the LINK, is in English, but is your solution. If you have difficulties, comment, I put an answer.

  • Hi, I’m okay, how are you? Well, I read the answers, I tried some and they didn’t work the getpass for example, it seems that the one that works is last of Forgottenumbrella but honestly I didn’t find it easy to understand how to apply it (I started studying a week ago), but I will keep trying with time, but thank you very much, someday I will be able to apply it.

  • Don’t erase the question- it’s a legitimate doubt - it just doesn’t have a simple answer!

Show 4 more comments

1 answer

8


That’s not how it works on the terminal.

Follows Brief History of Programming Input and Output

The idea of learning "print" and "input" first when we’re learning to program, or a new language, is that it’s the easiest input and output methods embedded in the language for user communication.

However, both functions refer to a time in computing when video monitors were not of such common use - the computer had a text printer, line by line, and a keyboard - the terminal "emulates" the printing of a paper report printing line by line. This is done in the operating system, which provides programs with a "standard input", a "standard output" and a "standard error output" - even today, most command line programs would work if the "standard output" was a line printer, instead of a terminal window.

print keeps printing line after line - what happens is that in languages like Python, it has sophisticated ways of crafting a string before sending it to the terminal.

The input, it emulates the input by the terminal - the user typed a line of text (or punched a card), and when pressing "enter" (or put the card), the line data was entered all at once.

There are ways to use the ending in a "random" way, you can print characters anywhere on the screen, read keystrokes without waiting for "enter", or do not echo "enter" to the terminal, avoiding line breaking. These shapes were also created back there - as soon as they put the video terminals, but for some reason, never became the standard form of terminal use. Some antigone programming languages have chosen to integrate this sophisticated use of the direct terminal into the language - for example, Cobol - but this implies that the programming language is "fixed" in a niche, always "relying on a random access terminal". Generic-use languages such as the C, Java, Python family have no preference for a more sophisticated input and output type than 'standard output' and 'standard input' at the language level - although they are flexible for you to be able to use a library for any type of input and output: a porgrama that uses its own window, a web program, a free graphical screen, such as a game screen, or a custom connection with distinct I/O devices such as webcams, microphones, Speakers And even, a random terminal, with access "out of order". However, none of these forms of I/O is linked to the common functions "print" and "input" (or equivalent in other languages).

For its users it is much better to do this than to try to re-invent the wheel on the terminal, leaving it "easier to use": for modern users, if they are not used to the terminal, however "chic" their program is on the terminal, it will continue to be alien. For modern users accustomed to the terminal (Developers, admin, etc...), a terminal program that escapes the conventions of entry and exit line by line also will be something alien.

What to do?

  • web development

If you want any input and output more sophisticated than print and input line by line, the best thing is change the input and output system of your program, and make it either a graphical program with its own window, or a web program - in this case, its default "input and output" is connected to the HTTP protocol, and the program generates an HTML page, with forms and CSS, which is displayed by the web browser - this can be done even if the program is local: the browser points to the computer itself where the program is running.

It is a whole different paradigm, it is a much more complex system than the "input" and "print" mechanism that we first learned, involves the use of several secondary languages (at least HTML) - but its program becomes something of use "real".

A practical way to make small programs that use webbrowser to display the graphical interface is by using the Flask micro-framework. It allows with the addition of an extra line to decorate its functions, they are automatically called from links or form submissions on web pages. The tutorials beyond the Hello World will plug in all the complexity necessary to have a modern web app, "production", but it is possible to have an application that manages a simple page, with a single form and response form. Typo pip install flask, and you’ll have everything you need to have flask working - here’s "hello world" - change the HTML to include a form with the fields you need (with the elements <input /> and <submit />), and use an if to detect if the request is a POST to process the form:

from flask import Flask
import datetime
app = Flask(__name__)

@app.route('/')
def hello_world():
    html = """<h1> Formulário </h1>
    <form method="post" action="#" >

    Entre com a data:
    <input type="text" name="dia" width="2">/
    <input type="text" name="mes" width="2">/
    <input type="text" name="ano" width="4"><br>
    <input type="submit" value="Enviar">
    </form>

    """
    if request.method == "POST":
        data = datetime.datetime(

            int(request.form["ano"]),
            int(request.form["mes"]),
            int(request.form["dia"]))
        )
        html = f"""<h1> Você digitou a data {data.isoformat()}</h1>"""

    return html 

In the terminal, in the same folder that this file is in, if it is called "test.py", type (in windows): set FLASK_APP=teste.py and on any other system (Linux, Mac): export FLASK_APP=teste.py, and then flask run. Open a browser at the address "http://localhost:5000" and use your program.

To sophisticate the application, please read and study the flask documentation - at some point it teaches how to put together the web front-end packages such as "bootstrap", "jquery", and so on... for a sophisticated presentation.

  • Graphical application

This is another paradigm that will still be more normal to its users, but also involves understanding a number of different concepts. Although, in most frameworks used, it does not need another auxiliary language. Python comes with the Tkinter library, which allows the development of applications complete with the graphic paradigm. Here is a reasonable post to understand how to do: https://www.devmedia.com.br/tkinter-interfaces-graficas-em-python/33956

Yeah, I read it so far, but what if I want use terminal??

As I described above, it is possible create such applications in the terminal. One way to do this that comes embedded in Python is with the "curses library" - https://docs.python.org/3.3/howto/curses.html . However, for the reasons I gave in the first part of the reply, microsoft chose not to evolve the windows terminal beyond the support of "print" and "input", so the "curses" of Python is not available by default in windows - the documentation linked above has how to circumvent this, but you will see that the thing becomes much more complicated anyway.

When reading the course documentation, you will see that its use is much, much more complex than we simply do with "print" and "input", but it still doesn’t change so much the idea of programming as a graphical application, or for the web: these two ways have to "respond to events" - with curses, your program can continue to be linear - that is, the idea of 'here the program to wait for a user input', as we do with the input.

There are ways to configure the terminal and change the input function so that you don’t need everything that curses offers, and, with two or three more functions, have the program "almost equal" what it was with "print" and "input". - but, as stated in the above section, it is reinventing the terminal wheel in a way that displeases everyone, including veteran terminal users. This wouldn’t work in windows - only on Mac and Linux, and it’s so "arcane" and forgotten that it’s virtually impossible to even do a search for how to do it (I tried). What exist are ANSI control characters - special sequences of printed characters that allow color change, or cursor placement in the terminal. (then, after an input, you can send the cursor back to the top row, and walk a certain number of characters forward). The sequence to send the cursor to the top line, for example, is "ESC [A" - can be written in Python as print("\x1b[A", end="") - change A to "C" to move the cursor forward. The complete documentation of these sequences is in https://en.wikipedia.org/wiki/ANSI_escape_code - but of course I do not recommend that you write your program using them. If you are really going to stay in the terminal, better learn to use curses.

  • Yeah, but it’s like?

Yes - as a rule, but there will always be "use cases" that are not covered - if you want to cover all, you end up having to rewrite the entire "curses".

n_input_previous_col = 0

def n_input(prompt='', end='\n'):
    global n_input_previous_col
    result = input(prompt)
    if end.startswith('\n'):
        print(end[1:], end='')
        n_input_previous_col = len(end) - 1
        return result
    positions = n_input_previous_col + len(prompt.split('\n')[-1]) + len(result)
    CSI = '\x1b['
    cursor_up = CSI + 'A'
    cursor_right = '{}{}C'.format(CSI, positions)
    print (cursor_up, cursor_right, sep='', end='')
    n_input_previous_col = positions
    return result

The above function more or less implements the "end" parameter for input - just call it in place of the normal input. It does this by detecting if the "end" is different from one that starts with " n", which the input always does, it moves the cursor back a row up, and does a guessing job on which column the typing stopped - moving the cursor to the right.

It works on Linux and Mac, and in some Windows terminal programs - for the standard terminals this has to be enabled - see here: https://superuser.com/questions/413073/windows-console-with-ansi-colors-handling/1050078#1050078 - don’t know Python no longer active by default.

Anyway, using the above function, on an ipython in a supported terminal, I could do it here:

In [17]: a = n_input('dia: ', end='');b=n_input('/',end='');c=n_input('/')
dia: 08/10/2018

In [18]: print(a, b, c)
08 10 2018

(One of the limitations of this function is that an input that does not start at the zero column of the terminal - even if it is the continuation of others - has to know in which column it starts. While only the "n_input" itself is used with the terminal, it accounts for the column in the global variable n_input_previous_col, but if you cross-link the calls anyway with print or other output, you will have to update this variable)

In short:

At the point where you want to make your application’s input and output more sophisticated for end users, you have to abandon "print" and "input" - and choose a path for your journey. Not much to do.

  • Awesome, thank you so much for the answer, it will be of great help!

  • I updated the answer with a full example of how to input without line break, despite all the explanation of why not.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.