Why does IDLE add a newline after my code? - python

On my saving a .py file, IDLE (Python 3.9 x64) will add a newline after the code itself. It is setting off my OCD while making me curious. For instance, take this entirely original last line of a program while coding:
print("Hello, world!")
Yet, when saved, it becomes:
print("Hello, world!")
# ghost line!
What is the significance of that extra lineā€”can I turn it off?

IDLE has made sure that a file being saved ends with a newline ('\n') since the first commit in 2000. I believe that at one time the Python compiler required that every line, including the last, be complete, ending with a newline. It may be more lax now, under some circumstances, but I am not sure. There may be other things one does with a file that could require the proper ending.
Ghosts do not exist, and neither does the ghost line. A line of 0 characters is not really a line. The cursor at the left margin after the last line is ready to start a new line.

It is the best practice of Python to have an extra line at the end of the code. If you explicitly go and delete the last line, then it won't be there. But, my suggestion would be to keep it. It's always better to follow best practices.

Related

Python - print long string in terminal but stay at the beginning of the string

I am writing a script that runs in the terminal and that displays a (long) multiple line string. My problem is that, when the string is printed, the terminal automatically places the cursor at the end of the string.
The string being longer than the number of lines in the terminal, I only see the last 72 lines of my string (my terminal window has 72 lines), so it forces to scroll up to the beginning of the string every time I run that script, and it turns out to be pretty annoying.
Is there a way to go back to the beginning of the string once it's printed?
End of string, the cursor is at the bottom:
Beginning of the string, ~200 lines above, where I want to be after the script runs:
I thought of using curses, but that seems to be overkill for what I am looking for.
Also, I'm on Mac OS and I don't particularly care about portability
While curses is the portable solution, try printing the sequence ESC [ H. It will likely work on all of the terminals you care about.
print "\033[H"
Reference:
https://en.wikipedia.org/wiki/ANSI_escape_code
Re your comment you made on Aug 28, 2015 at 1:51:
I think what you are looking for is printing this escape code:
print("\033[F")

Dynamic single-line printing in Python (time?)

I'd like to make a simple clock (CLI) that prints the time into one line, and updates it every second. Is this even possible? Should I just print a new line every second?
This is what I have at the moment, which functions terribly:
import calendar, time
a = 1
while a == 1:
print (calendar.timegm(time.gmtime()))
If I understand, what you want to do is write the time, then, a second later, overwrite it with the new time, and so on.
On most terminals, printing a carriage return without a newline will take you back to the start of the same line. So, you can almost just do this:
print('\r{}'.format(calendar.timegm(time.gmtime())), end='')
In general, there's a problem with this: the carriage return doesn't erase the existing text, it just lets you overwrite it. So, what happens if the new value is shorter than the old one? Well, in your case, that isn't possible; you're printing a 10-digit number that can never turn into a 9-digit number. But if it were a problem, the easiest solution would be to change that {} to something like {<70}, which will pad a short line with spaces, up to 70 characters. (Of course if your lines could be longer than 70 character, or your terminal could be narrower than 70, don't use that number.)
Meanwhile, if you just do this over and over as fast as possible, you're wasting a lot of CPU and I/O, and possibly screwing up your terminal's scrollback buffer, and who knows what else. If you want to do this once per second, you should sleep for a second in between.
So:
while True:
print('\r{}'.format(calendar.timegm(time.gmtime())))
time.sleep(1)
If you want to get fancy, you can take over the whole terminal with curses on most non-Windows platforms, msvcrt console I/O on Windows, or even manually printing out terminal escape sequences. But you probably don't want to get fancy.
print function print newline (\n) after the string you passed. Specify carriage return (\r) explicitly does what you want.
To print every second, call time.sleep(1) after printing.
import calendar
import time
while 1:
print(calendar.timegm(time.gmtime()), end='\r')
time.sleep(1)
UPDATE
To make cursor remains at the end of the line, prepend \r:
print('\r', calendar.timegm(time.gmtime()), sep='', end='')

^H ^? in python

Some terminals will send ^? as backspace, some other terminals will send ^H.
Most of the terminals can be configured to change their behavior.
I do not want to deal with all the possible combinations but I would like to accept both ^? and ^H as a backspace from python.
doing this
os.system("stty erase '^?'")
I will accept the first option and with
os.system("stty erase '^H'")
I will accept the second one but the first will be no longer available.
I would like to use
raw_input("userinput>>")
to grab the input.
The only way I was able to figure out is implementing my own shell which works not on "raw based input" but on "char based input".
Any better (and quicker) idea?
The built-in function raw_input() (or input() in Python 3) will automatically use the readline library after importing it. This gives you a nice and full-feautured line editor, and it is probably your best bet on platforms where it is available, as long as you don't mind Readline having a contagious licence (GPL).
I don't know your question exactly. IMO, you need a method to read some line-based text(including some special character) from console to program.
No matter what method you use, if read this character have special mean in different console, you should confront a console(not only system-specific, but also console-specific) question, all text in console will be store in buffer first, and then show in screen, finally processed and send in to your program. Another way to surround this problem is to use a raw line-obtaining console environment.
You can add a special method(a decorator) to decorate the raw_input() or somewhat input method to process special word.
After solved that question
using this snippet can deal with input,:
def pre():
textline=raw_input()
# ^? should replace to the specific value.
textline.replace("^?","^H")
return textline
To be faster, maybe invoke some system function depend on OS is an idea. But in fact, IO in python is faster enough for common jobs.
To fix ^? on erase do stty erase ^H

indent python file (with pydev) in eclipse

I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D in visual studio, which formats and indents all the source code lines automatically?
If you want to change from 2 space to 4 space indentation (for instance), use "Source->Convert space to tab" with 2 spaces, then "Soruce->Convert tab to space" with 4 spaces.
I ... don't think this question makes sense. Indentation is syntax in Python. It doesn't make sense to have your IDE auto-indent your code. If it's not indented properly already, it doesn't work, and the IDE can't know where your indentation blocks begin and end. Take, for example:
# Valid Code
for i in range(10):
b = i
for j in range(b):
c = j
# Also Valid Code.
for i in range(10):
b = i
for j in range(b):
c = j
There's no possible way that the IDE can know which of those is the correct version, or what your intent is. If you're going to write Python code, you're going to have to learn to manage the indentation. There's no way to avoid it, and expecting the IDE to magically clean it up and still get the desired result out of it is pretty much impossible.
Further example:
# Valid Code.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
# Again, also valid code, wildly different behavior.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
The first will produce a list of strings, then print the joined result to the console 1 time. The second will still produce a list of strings, but prints the cumulative joined result for each iteration of the loop - 100 print statements. The two are both 100% syntactically correct. There's no problem with them. Either of them could be what the developer wanted. An IDE can't "know" which is correct. It could, very easily incorrectly change the first version to the second version. Because the Language uses Indentation as Syntax, there is no way to configure an IDE to perform this kind of formatting for you.
Although auto-indentation is not a feature of PyDev because of the language design you should be able to indent with a simple tab. Just select the lines you want to indent and press Tab. If you want to unindent lines you have to press Shift+Tab.
Thats all.
It is much easier:
Select multiple lines
Press Tab to indent (move right), Shift + Tab to unindent (move left) all selected
lines.
Indentation is syntactically significant; consider the difference between
for i in range(5):
print i
print "done"
and
for i in range(5):
print i
print "done"
However, it certainly makes sense for the IDE to be able to normalize the existing indentation (e.g. apply a consistent number of spaces/tabs at each level).
Currently PyDev does not support such a feature; Pydev author Fabioz at one point expressed interest in adding it in the future and indicated that for now you can use the supplied reindent.py script to do it.
Obviously this is only for Pydev, but I've worked out that you can get the very useful functions "Shift Right" and "Shift Left" (mapped by default to CTRL + ALT + . and CTRL + ALT + ,) to become useful by changing their keybindings to "Pydev Editor Scope" from "Pydev View". This effectively indents/dedents all lines that you've selected as much as you'd like
I think that what you're looking for is some kind of shortcut in Eclipse/PyDev so that the selected code can be idented all at once. Just like when you create a new "if" or a "for" loop above a block of code and then need to rearrange the identation. The IDLE Editor has the "Ctrl + ]" shortcut that works exactly that way. It seems that the PyDev in Eclipse doesnt have something like that as far as I know.
One can also select the lines, right click, then shift right / shift left
It seems source formatting is still not available in PyDev.
For one off instances I found this web app does the job nicely.
http://pythoniter.appspot.com/
Like earlier said python requires to indent your code, so for other things like: space between variables passed as arguments to methods, etc., one can use ctrl+shift+f to format the code. This what is used for java, I tried for pydev and does some formatting.

vim highlighting everything in red

I added a print line to a python script while the script was executing, and now all the text is highlighted in red when I open the file. Opening and closing the file doesn't get rid of it. Opening a second python file momentarily fixed the problem, but then closing file and reopening brought the problem back. Now it wont go away at all. Any body know what could cause this?
This happens sometimes in vim when it goes to highlight syntax on multi-line comments. Occasionally everything after the multi-line comment also becomes colored the same as the comment.
I am unsure whether this is a legit bug in vim, or in the actual syntax settings for Python (e.g. python.vim), but I definitely experience this from time-to-time.
For a quick fix, you might try typing:
:hi Error NONE
And then hit Enter.
Old thread, but hope this helps.
By mistake I did a "/." on my vim screen, which highlighted all lines in red. If I open any other file, the red highlighting stays.
Try searching for some other keyword, let's say "/word" - doesn't matter word exists or not. It restores the color.
You probably have an unterminated multiline string. They start and end with either three single or three double quotes.
''' <== this is the start of a multiline string
this is still in the string
this is the last line '''
As per this article http://vim.wikia.com/wiki/Fix_syntax_highlighting, I mapped F12 to resync the syntax highlighting from the start of the file. It has worked better in some instances where <ctrl-l> didn't.
noremap <F12> <Esc>:syntax sync fromstart<CR>
inoremap <F12> <C-o>:syntax sync fromstart<CR>

Categories

Resources