This question already has answers here:
Getting SyntaxError for print with keyword argument end=' '
(17 answers)
Closed 8 years ago.
This is the function for printing all values in a nested list (taken from Head first with Python).
def printall(the_list, level):
for x in the_list:
if isinstance(x, list):
printall(x, level=level + 1)
else:
for tab_stop in range(level):
print("\t", end='')
print(x)
The function is working properly.
The function basically prints the values in a list and if there is a nested list then it print it by a tab space.
Just for a better understanding, what does end=' ' do?
I am using Python 3.3.5
For 2.7
f = fi.input( files = 'test2.py', inplace = True, backup = '.bak')
for line in f:
if fi.lineno() == 4:
print line + '\n'
print 'extra line'
else:
print line + '\n'
as of 2.6 fileinput does not support with.
This code appends 3 more lines and prints the appended text on the 3rd new line. and then appends a further 16 empty lines.
The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed
Eg: - print ("hello",end=" +") will print hello +
See the documentation for the print function: print()
The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.
i am very new in python (and programming in general) and here is my issue. i would like to replace (or delete) a part of a string from a txt file which contains hundreds or thousands of lines. each line starts with the very same string which i want to delete.
i have not found a method to delete it so i tried a replace it with empty string but for some reason it doesn't work.
here is what i have written:
file = "C:/Users/experimental/Desktop/testfile siera.txt"
siera_log = open(file)
text_to_replace = "Chart: Bar Backtest: NQU8-CME [CB] 1 Min #1 | Study: free dll = 0 |"
for each_line in siera_log:
new_line = each_line.replace("text_to_replace", " ")
print(new_line)
when i print it to check if it was done, i can see that the lines are as they were before. no change was made.
can anyone help me to find out why?
each line starts with the very same string which i want to delete.
The problem is you're passing a string "text_to_replace" rather than the variable text_to_replace.
But, for this specific problem, you could just remove the first n characters from each line:
text_to_replace = "Chart: Bar Backtest: NQU8-CME [CB] 1 Min #1 | Study: free dll = 0 |"
n = len(text_to_replace)
for each_line in siera_log:
new_line = each_line[n:]
print(new_line)
If you quote a variable it becomes a string literal and won't be evaluated as a variable.
Change your line for replacement to:
new_line = each_line.replace(text_to_replace, " ")
This question already has an answer here:
python lxml tree, line[] creating multiple lines, desire single line output
(1 answer)
Closed 7 years ago.
In a script im working on I do the following:
data["serial"] = md5.new(json.dumps(data["data"])).hexdigest()
...
...
lst = serialFile.readlines()
if(len(lst) > 0):
lastLine = lst[len(lst) - 1]
...
...
print "lLn : " , lastLine
print "md5 : " , str(data["serial"])
if lastLine == data["serial"]:
I can verify that when I print out lLn and md5 they are the same. I feel like i should be tripping the logic statement ... but i do not ...
Also i have tried using :
if lastLine == str(data["serial"]):
I am still fairly new to Python ... what am i missing here ?
Assuming readlines() is done on an open file handle, it will read the entire stream out into a list of lines, with lines including the carriage return and newline characters. You want to call rstrip() on the lines to remove all the extra newline and carriage return characters that might be present. If you also have other whitespace characters at the end that you want to remove you would want to call rstrip('\r\n') instead.
Another hint: you don't need to find the length of the list to get the last element, you can simply do lst[-1] in your case.
Putting it all together, you would do something like
lst = serialFile.readlines()
if(len(lst) > 0):
lastLine = lst[-1].rstrip('\r\n')
I was surprised that I couldn't find this question on here.
I would like to take extract one line from a telnet response and make it a variable. (actually one number from that line). I can extract up to where I need using telnet.read_until(), but the whole beginning is still there. The printout shows different statuses of a machine.
The line I am trying to get is formatted like this:
CPU Utilization : 5 %
I really only need the number, but there are many ':' and '%' characters in the rest of the output. Can anyone help me extract this value? Thanks in advance!
Here is my code (this reads the whole output and prints):
import telnetlib, time
print ("Starting Client...")
host = input("Enter IP Address: ")
timeout = 120
print ("Connecting...")
try:
session = telnetlib.Telnet(host, 23, timeout)
except socket.timeout:
print ("socket timeout")
else:
print("Sending Commands...")
session.write("command".encode('ascii') + b"\r")
print("Reading...")
output = session.read_until(b"/r/n/r/n#>", timeout )
session.close()
print(output)
print("Done")
Edit: some example of what an output could be:
Boot Version : 1.1.3 (release_82001975_C)
Post Version : 1.1.3 (release_82001753_E)
Product VPD Version : release_82001754_C
Product ID : 0x0076
Hardware Strapping : 0x004C
CPU Utilization : 5 %
Uptime : 185 days, 20 hours, 31 minutes, 29 seconds
Current Date/Time : Fri Apr 26 17:50:30 2013
As you say in the question:
I can extract up to where I need using telnet.read_until(), but the whole beginning is still there.
So you can get all of the lines up to and including the one you want into a variable output. The only thing you're missing is how to get just the last line in that output string, right?
That's easy: just split output into lines and take the last one:
output.splitlines()[:-1]
Or just split off the last line:
output.rpartition('\n')[-1]
This doesn't change output, it's just an expression that computes a new value (the last line in output). So, just doing this, followed by print(output), won't do anything visibly useful.
Let's take a simpler example:
a = 3
a + 1
print(a)
That's obviously going to print 3. If you want to print 4, you need something like this:
a = 3
b = a + 1
print(b)
So, going back to the real example, what you want is probably something like this:
line = output.rpartition('\n')[-1]
print(line)
And now you'll see this:
CPU Utilization : 5 %
Of course, you still need something like Johnny's code to extract the number from the rest of the line:
numbers = [int(s) for s in line.split() if s.isdigit()]
print(numbers)
Now you'll get this:
['5']
Notice that gives you a list of one string. If you want just the one string, you still have another step:
number = numbers[0]
print(number)
Which gives you:
5
And finally, number is still the string '5', not the integer 5. If you want that, replace that last bit with:
number = int(numbers[0])
print(number)
This will still print out 5, but now you have a variable you can actually use as a number:
print(number / 100.0) # convert percent to decimal
I'm depending on the fact that telnet defines end-of-line as \r\n, and any not-quite-telnet-compatible server that gets it wrong is almost certainly going to use either Windows-style (also \r\n) or Unix-style (just \n) line endings. So, splitting on \n will always get the last line, even for screwy servers. If you don't need to worry about that extra robustness, you can split on \r\n instead of \n.
There are other ways you could solve this. I would probably either use something like session.expect([r'CPU Utilization\s*: (\d+)\s*%']), or wrap the session as an iterator of lines (like a file) and then just do write the standard itertools solution. But this seems to be simplest given what you already have.
As I understand the problem, you want to select 1 line out of a block of lines, but not necessarily the last line.
The line you're interested in always starts with "CPU Utilization"
This should work:
for line in output.splitlines():
if 'CPU Utilization' in line:
cpu_utilization = line.split()[-2]
If you want to get only numbers:
>>> output = "CPU Utilization : 5 %"
>>> [int(s) for s in output.split() if s.isdigit()]
[5]
>>> output = "CPU Utilization : 5 % % 4.44 : 1 : 2"
>>> [int(s) for s in output.split() if s.isdigit()]
[5, 4.44, 1, 2]
EDIT:
for line in output:
print line # this will print every single line in a loop, so you can make:
print [int(s) for s in line.split() if s.isdigit()]
In [27]: mystring= "% 5 %;%,;;;;;%"
In [28]: ''.join(c for c in mystring if c.isdigit())
Out[28]: '5'
faster way :
def find_digit(mystring):
return filter(str.isdigit, mystring)
find_digit(mystring)
5
I want to run a script, which basically shows an output like this:
Installing XXX... [DONE]
Currently, I print Installing XXX... first and then I print [DONE].
How can I instead print Installing xxx... and [DONE] on the same line?
For the specific problem of writing a new message on the same line, replacing what was there before, please see How to overwrite the previous print to stdout?. Most answers here interpreted the question as being about writing new text at the end of the current line.
For the problem of using a single print to output multiple things at once, see How can I print multiple things (fixed text and/or variable values) on the same line, all at once?.
Python 3 Solution
The print() function accepts an end parameter which defaults to \n (new line). Setting it to an empty string prevents it from issuing a new line at the end of the line.
def install_xxx():
print("Installing XXX... ", end="", flush=True)
install_xxx()
print("[DONE]")
Python 2 Solution
Putting a comma on the end of the print() line prevents print() from issuing a new line (you should note that there will be an extra space at the end of the output).
def install_xxx():
print "Installing XXX... ",
install_xxx()
print "[DONE]"
You can simply use this:
print 'something',
...
print ' else',
and the output will be
something else
no need to overkill by import sys. Pay attention to comma symbol at the end.
Python 3+
print("some string", end=""); to remove the newline insert at the end. Read more by help(print);
You should use backspace '\r' or ('\x08') char to go back on previous position in console output
Python 2+:
import time
import sys
def backspace(n):
sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
sys.stdout.write(s) # just print
sys.stdout.flush() # needed for flush when using \x08
backspace(len(s)) # back n chars
time.sleep(0.2) # sleep for 200ms
Python 3:
import time
def backline():
print('\r', end='') # use '\r' to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print(s, end='') # just print and flush
backline() # back to the beginning of line
time.sleep(0.2) # sleep for 200ms
This code will count from 0% to 100% on one line. Final value will be:
> python test.py
100%
Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?
Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.
Most simple:
Python 3
print('\r' + 'something to be override', end='')
It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.
None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:
def print_no_newline(string):
import sys
sys.stdout.write(string)
sys.stdout.flush()
To test it:
import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')
"hello " will first print out and flush to the screen before the sleep. After that you can use standard print.
sys.stdout.write will print without return carriage
import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")
http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines
Python appends newline as an end to print. Use end=' ' for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.
print('Foo', end=' ')
print('Bar')
This simple example will print 1-10 on the same line.
for i in range(1,11):
print (i, end=" ")
Print has an optional end argument, it is what printed in the end.
The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")
If you want to overwrite the previous line (rather than continually adding to it), you can combine \r with print(), at the end of the print statement. For example,
from time import sleep
for i in xrange(0, 10):
print("\r{0}".format(i)),
sleep(.5)
print("...DONE!")
will count 0 to 9, replacing the old number in the console. The "...DONE!" will print on the same line as the last counter, 9.
In your case for the OP, this would allow the console to display percent complete of the install as a "progress bar", where you can define a begin and end character position, and update the markers in between.
print("Installing |XXXXXX | 30%"),
Here a 2.7-compatible version derived from the 3.0 version by #Vadim-Zin4uk:
Python 2
import time
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print '{0}\r'.format(s), # just print and flush
time.sleep(0.2)
For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn't make use of the integer argument and could probably be done away with altogether.
Python 3
import time
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print('{0}\r'.format(s), end='') # just print and flush
time.sleep(0.2) # sleep for 200ms
Both have been tested and work.
This is a very old thread, but here's a very thorough answer and sample code.
\r is the string representation of Carriage Return from the ASCII character set. It's the same as octal 015 [chr(0o15)] or hexidecimal 0d [chr(0x0d)] or decimal 13 [chr(13)]. See man ascii for a boring read. It (\r) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It's the CR part of CRLF which means Carriage Return and Line Feed.
print() is a function in Python 3. In Python 2 (any version that you'd be interested in using), print can be forced into a function by importing its definition from the __future__ module. The benefit of the print function is that you can specify what to print at the end, overriding the default behavior of \n to print a newline at the end of every print() call.
sys.stdout.flush tells Python to flush the output of standard output, which is where you send output with print() unless you specify otherwise. You can also get the same behavior by running with python -u or setting environment variable PYTHONUNBUFFERED=1, thereby skipping the import sys and sys.stdout.flush() calls. The amount you gain by doing that is almost exactly zero and isn't very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.
And a sample. Note that this runs perfectly in Python 2 or 3.
from __future__ import print_function
import sys
import time
ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}
for i in range(1, ANS + 1):
if i in FACTORS:
print('\r{0:d}'.format(i), end='')
sys.stdout.flush()
time.sleep(ANS / 100.0)
else:
print()
This solution in Python 3.X specific:
When I need to do this, I'll generally just use
end=' '
For example:
# end='' ends the output with a <space>
print("Welcome to" , end = ' ')
print("stackoverflow", end = ' ')
This outputs as:
Welcome to stackoverflow
The space in end= can be replaced with any character. For example,
print("Welcome to" , end = '...')
print("stackoverflow", end = '!')
Which outputs as:
Welcome to...stackoverflow!
print() has a built in parameter "end" that is by default set to "\n"
Calling print("This is America") is actually calling print("This is America", end = "\n").
An easy way to do is to call print("This is America", end ="")
Just in case you have pre-stored the values in an array, you can call them in the following format:
for i in range(0,n):
print arr[i],
Found this Quora post, with this example which worked for me (python 3),
which was closer to what I needed it for (i.e. erasing the whole previous line).
The example they provide:
def clock():
while True:
print(datetime.now().strftime("%H:%M:%S"), end="\r")
For printing the on the same line, as others have suggested, just use end=""
I found this solution, and it's working on Python 2.7
# Working on Python 2.7 Linux
import time
import sys
def backspace(n):
print('\r', end='') # use '\r' to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
sys.stdout.write(string)
backspace(len(s)) # back for n chars
sys.stdout.flush()
time.sleep(0.2) # sleep for 200ms