Random space at the end of printed outputs - python

My code says its missing a new line after it is submitted
Here is my code
import math
r = math.pow(2,1/12)
f0 = float(input(''))
print('{:.2f}'.format(f0), end = " ")
for n in range(1,5):
fn = f0 * math.pow(r,n)
print('{:.2f}'.format(fn), end = ' ')
print ()
It is showing that there is an extra space at the end.

this one :
import math
r = math.pow(2,1/12)
f0 = float(input(''))
print('{:.2f}'.format(f0), end='') # < remove space
for n in range(1,5):
fn = f0 * math.pow(r,n)
print(' ',end='') # < put space there
print('{:.2f}'.format(fn), end='')
print ()
outs:
% python3 1.py
10
10.00 10.59 11.22 11.89 12.60
there are no space after 12.60

Related

how can I align the output horizantally with python?

can anyone take a look to my code and tell me what I'm missing?
I am trying to solve a freecodingcamp project called arithmetic formatter
this is my code:
def arithmetic_arranger(lst):
for x in lst:
if '+' in x:
x = x.split('+')
a = int(x[0])
b = int(x[1])
upa = str(a)
downb = str(b)
total = str(a + b)
s_total = str(total)
plusAndB = '+ ' + downb
line = '---------'
print('{:>8}'.format(upa),'\n','{:>7}'.format(plusAndB),'\n', '{:>8}'.format(line[0:len(s_total)]),'\n','{:>7}'.format(s_total))
if '-' in x:
y = x.split('-')
c = int(y[0])
d = int(y[1])
substracion = c - d
s_sub = str(substracion)
subAndD = '- ' + str(d)
line = '---------'
print('{:>8}'.format( c),'\n','{:>7}'.format(subAndD),'\n', '{:>8}'.format(line[0:len(s_sub) + 2]),'\n','{:>7}'.format(s_sub))
print('')
print(arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"]))
I want the results to be aligned as follows:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
no matter what I have tried I always get this output:
32
+ 8
--
40
1
- 3801
-------
-3800
9999
+ 9999
-----
19998
523
- 49
-----
474
I left inline comments to explain what the code does
def output(seq):
final = [] # final output list
for expression in seq:
op = "+" if "+" in expression else "-" # op will represent the operator
top,bottom = [i.strip() for i in expression.split(op)] # split equation
ibottom = int(bottom) if op == "+" else int(bottom) * -1 # make bottom
# negative if
# operater is a
# minus
solution = str(sum([i for i in [int(top), ibottom]])) # sum solution
bottom = op + " " + bottom # add operator to bottom
out = [] # formated output list
mx = max(int(i) for i in [top, bottom, solution]) # largest string
for val in [top, bottom, solution]:
out.append(str(val).rjust(mx, " ")) # pad with spaces
out.insert(2, ("-" * mx)) # insert line before answer
final.append(out)
return final # return all solutions
out = output(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"])
# join lines from each solution into their own lines to print them one at a time
print('\n'.join([(' '.join([out[i][j] for i in range(len(out))])) for j in range(len(out))]))
output
32 1 9999 523
+ 8 - 3801 + 9999 - 49
--- ------ ------ ----
40 -3800 19998 474

How to convert elapsed time string to seconds in Python

Does anyone know if there is an "easy" function which will convert the following elapsed time string to seconds?
2d1h39m53s
Depending on how much time has elapsed, not all the fields will be present.
I've looked at strptime and datetime but nothing seemed to fit the bill without writing my own function for this. Just looking to save some time.
Thx
I wrote it to days before to clearly verify the runtime. After the two defs below just write 'tic()' at the start point in your code where you want count and 'toc()' at the end point, and it will give you a clear time data to read. Hope it helps.
import time
import math
def tic():
global startTime_for_tictoc
startTime_for_tictoc = time.time()
def toc():
if 'startTime_for_tictoc' in globals():
tf = time.time() - startTime_for_tictoc;
if tf < 60:
print("\nElapsed time: %f seconds.\n" % tf)
elif 60 < tf < 3600:
mm = math.floor(tf/60)
ss = tf - (60*mm)
print("\nElapsed time: %d minute(s) and %f seconds.\n" % (mm, ss))
elif 3600 < tf < 86400:
hh = math.floor(tf/3600)
mm = math.floor((tf-(hh*3600))/60)
ss = tf - (hh*3600) - (60*mm)
print("\nElapsed time: %d hour(s) %d minute(s) and %f seconds.\n" % (hh, mm, ss))
elif tf > 86400:
dd = math.floor(tf/86400)
hh = math.floor((tf-(dd*86400))/3600)
mm = math.floor((tf-(dd*86400)-(hh*3600))/60)
ss = tf - (86400*dd) - (hh*3600) - (60*mm)
print("\nElapsed time: %d day(s) %d hour(s) %d minute(s) and %f seconds.\n" % (dd, hh, mm, ss))
else:
print("\nToc: start time not set")
Not sure if there is a function out there but this will get the job done. Will work with values such as "2d1h53s" as well.
d = []
h = []
m = []
s = []
sd = 0
sh = 0
sm = 0
ss = 0
str = "2d1h39m53s"
i = 0
if str.find("d") > 0:
i = str.find("d")
d.append(str[0:i])
str = str[i:]
if str.find("h") > 0:
i = str.find("h")
h.append(str[1:i])
str = str[i:]
if str.find("m") > 0:
i = str.find("m")
m.append(str[1:i])
str = str[i:]
if str.find("s") > 0:
i = str.find("s")
s.append(str[1:i])
str = str[i:]
try:
sd = float(d[0]) * 24 * 60 * 60
except:
sd = 0
try:
sh = float(h[0]) * 60 * 60
except:
sh = 0
try:
sm = float(m[0]) * 60
except:
sm = 0
try:
ss = float(s[0])
except:
ss = 0
print("seconds")
sec = sd + sh + sm + ss
print(sec)
If your datetime has exactly the given format you could do the following:
import re
import numpy as np
from functools import reduce
split_strings = ['D', 'h','m','s']
def datestring_to_seconds(datestring):
values_and_units = [(int(string[:-1]), string[-1]) for string in [re.search(f"([0-9]+){split_string}",
f"{datestring}".replace('d', 'D')).group(0) for split_string in split_strings]]
return reduce(lambda x,y : x+y, [np.timedelta64(*x) for x in values_and_units])/np.timedelta64(1, 's')
result
datestring_to_seconds("2d1h39m53s")
178793.0
Some explanation:
First search in the string for any to a match of up to two digits in front of one of the split_strings (e.g. 39m) then we convert this to a tuple (39, "m"). We perform this operation with every string in split_strings and save the result in the list values_and_units, which looks in our special case like this:
[(2, 'D'), (1, 'h'), (39, 'm'), (53, 's')]
Each element of these can now be casted to a numpy timedelta64. The reduce operation adds up all the timedeltas and dividing by a np.timedelta64(1, 's') gives us a float with the desired seconds.
Here is a pure python solution.
import re
s = '2d1h39m53s'
d = {'d':86400,'h':3600, 'm':60, 's':1}
secs = 0
m = re.match(r'(\d+)([dhms])', s)
while m is not None:
secs += int(m.group(1)) * d[m.group(2)]
s = re.sub(r'\d+[dhms]', '', s, 1)
m = re.match(r'(\d+)([dhms])', s)
print(secs)
print(secs)
Prints: 178793
EDIT: To use match.end() to locate beginning of next search. Not destructive of string, s, and a cleaner solution.
import re
s = '2d1h39m53s'
d = {'d':86400,'h':3600, 'm':60, 's':1}
secs = 0
pat = re.compile('(\d+)([dhms])')
m = pat.search(s)
while m is not None:
pos = m.end()
secs += int(m.group(1)) * d[m.group(2)]
m = pat.search(s, pos)
print(secs)

Catching stdout and camera frames in realtime from subprocess

I have a wireless sensor node that transmits wirelessly to a receiver connected to my computer. I use this command to see the data in real time
sudo stdbuf -o0 ./pip_sense.v2 l l | stdbuf -o0 grep -P "TX:03(376|004)
I am new to Python, but I was able to develop a piece of code as show below to capture the stdout and takes frames from a camera connected to the same computer. That is when a packet (data) is received, at that timestamp, a frame will be captured.
It is working fine, except the fact that its running slow. I am running my sensor at a rate of 10 Hz (transmitting every 0.1 sec.) but the code does what is required at a slower rate. I know that is because I am using cv2.imwrite() (I commented out this part and that helped in reducing the delay). But also, as discussed in this post and its said (as I understand) that using shell=True can invoke extra shell process and thus increase the delay.
Also, looking at this, Popen() seems to be causing delays as well. A solution is proposed in the second link, but I do not really understand how to modify it to work for me.
#!/usr/bin/env python
from subprocess import Popen, PIPE
import time
import sys
import cv2
import os
import csv
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from collections import OrderedDict
from datetime import datetime
PIP_CMD = 'sudo stdbuf -o0 ./pip_sense.v2 l l | stdbuf -o0 grep -P "TX:03(376|004)"'
def run(command):
process = Popen(command, stdout=PIPE, shell=True)
while True:
line = process.stdout.readline().rstrip()
if not line:
break
yield line
print ('Starting...')
def createFolder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except OSError:
print ('Error: Creating directory. ' + directory)
createFolder('/home/piptag/pip-test/capture_webcam/EXPERIMENTS')
file1 = open('/home/piptag/pip-test/capture_webcam/EXPERIMENTS/3376.txt','w')
file1.write("Time Stamp \t TX ID \t RSSI \tSEQ NO \tCAP \tX-Axis \tY-Axis \tZ-Axis \t X \t Y \t Z \n") # Header line
file1.write("-------------------------------------------------------------------------------------------------------------------------------------\n")
file2 = open('/home/piptag/pip-test/capture_webcam/EXPERIMENTS/3004.txt','w')
file2.write("Time Stamp \t TX ID \t RSSI \tSEQ NO \tX-Axis \tY-Axis \tZ-Axis \t X \t Y \t Z \n") # Header line
file2.write("-------------------------------------------------------------------------------------------------------------------------------------\n")
dirname = "/home/piptag/pip-test/capture_webcam/EXPERIMENTS/"
def save_webcam(dirname):
cam = cv2.VideoCapture(-1) # was getting error (V4L: can't open camera by index 0), thus changes it to -1
jpg_quality = 75
frame_number = 0
if cam.isOpened():
ret_val, img = cam.read()
else:
ret_val = False
timestamp = int(TS)
path = dirname + str(tx) + str("-") + str(timestamp) + ".jpg"
cv2.imwrite(path, img, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality])
frame_number = frame_number + 1
##this is the end of the camera program
def twos_comp(val, bits):
"""compute the 2's compliment of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
#########################################MAIN###################################
if __name__ == "__main__":
for line in run(PIP_CMD):
raw_data = line.split('\t')
if len(raw_data) > 1:
TS = raw_data[0][3:]
tx = raw_data[3].split(':')[-1]
rssi = float(raw_data[4][5:])
crc_ok = True if (raw_data[5] != b'BAD CRC') else False
no_drop = True if (raw_data[1] == b'Drop:0') else False
# If CRC check is ok and no drop, process the packet
if crc_ok and no_drop:
data = raw_data[-1].split(':')[-1].split()
cat = ""
for i in data:
cat += str(i)
if tx == '03376':
save_webcam(dirname)
print data
CapStatus=data[1]
if CapStatus == '50':
Cap='0'
elif CapStatus == '51':
Cap='1'
SEQNO1=str(int((data[2]),16))
x_axis1=data[3]+data[4]
y_axis1=data[5]+data[6]
z_axis1=data[7]+data[8]
TX1=tx
x1 = twos_comp(int(x_axis1,16), 16) * 0.0039 #* 9.80665 #the value is multiplied by 0.004 as the ADXL345 reports data as 4mg per 1lsb
y1 = twos_comp(int(y_axis1,16), 16) * 0.0039 #* 9.80665 #the value is multiplied by 0.004 as the ADXL345 reports data as 4mg per 1lsb
z1 = twos_comp(int(z_axis1,16), 16) * 0.0039 #* 9.80665 #the value is multiplied by 0.004 as the ADXL345 reports data as 4mg per 1lsb
st1 = str(TS) + "\t "+ "{:<5}".format(str (TX1)) + "\t" + "{:<10}".format(str (rssi)) + "{:<5}".format(SEQNO1) + "\t" + "{:<5}".format(str (Cap)) + "\t" + "{:<5}".format(str (x_axis1)) + "\t" + "{:<5}".format(str (y_axis1)) + "\t"+ "{:<5}".format(str(z_axis1)) + "\t" + "{:<5}".format(str(x1)) + "\t" + "{:<5}".format(str(y1)) + "\t" + "{:<5}".format(str(z1)) +"\n"
file1.write(st1)
elif tx == '03004':
save_webcam(dirname)
print data
SEQNO2=str(int((data[1]),16))
x_axis2=data[2]+data[3]
y_axis2=data[4]+data[5]
z_axis2=data[6]+data[7]
TX2=tx
x2 = twos_comp(int(x_axis2,16), 16) * 0.0039 #* 9.80665 #the value is multiplied by 0.004 as the ADXL345 reports dataas 4mg per 1lsb
y2 = twos_comp(int(y_axis2,16), 16) * 0.0039 #* 9.80665 #the value is multiplied by 0.004 as the ADXL345 reports data as 4mg per 1lsb
z2 = twos_comp(int(z_axis2,16), 16) * 0.0039 #* 9.80665 #the value is multiplied by 0.004 as the ADXL345 reports data as 4mg per 1lsb
st2 = str(TS) + "\t "+ "{:<5}".format(str (TX2)) +"\t "+ "{:<10}".format(str (rssi)) + "{:<5}".format(SEQNO2) + "\t" + "{:<5}".format(str (x_axis2)) + "\t"+ "{:<5}".format(str (y_axis2)) + "\t"+ "{:<5}".format(str(z_axis2))+ "\t"+"{:<5}".format(str(x2)) + "\t" + "{:<5}".format(str(y2))+ "\t"+ "{:<5}".format(str(z2)) +"\n"
file2.write(st2)
file1.close()
file2.close()
I appreciate any help
Thank you
Update:
I got this advice from a friend and it worked.
Calling the cam = cv2.VideoCapture(-1) outside the save_webcam function (as a global variable) reduced the delays a lot.
In this case, the camera will be turned on one time and then capturing images will be done each time save_webcam is called...hence, turning on and off the camera was slowing the process.
However, I would like to enhance the program more, as it get stuck sometimes. So, anyone understands what is in this post and how my stdout part should be modified, then please comment here. I appreciate this.

Python stange behaviour when acessing list elements

This small scripts makes exactly what I need.
#!/usr/bin/python
import os
import fileinput
import sys
import shutil
import glob
import time
def replaceAll1(files,searchExp,replaceExp):
for line in fileinput.input(files, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
param1 = [1,2,3]
param2 = [1,2,3]
param3 = [1,2,3]
for i in xrange(len(param1)):
for ii in xrange(len(param2)):
for iii in xrange(len(param3)):
os.system("cp -a cold.in input.in")
old_param1 = "param1 = 1"
old_param2 = "param2 = 1"
old_param3 = "param3 = 1"
new_param1 = "param1 = " + str(param1[i])
new_param2 = "param2 = " + str(param2[ii])
new_param3 = "param3 = " + str(param3[iii])
replaceAll1('input.in',old_param1,new_param1)
replaceAll1('input.in',old_param2,new_param2)
replaceAll1('input.in',old_param3,new_param3)
time.sleep(4)
It enters in a configuration file and replaces sequentially the input parameters according to the lists that are accessed by the loop indexes. It is simple a combination of all the three parameters between each other.
# Input file
param1 = 1 # --- Should be [1,2,3]
param2 = 1 # --- Should be [1,2,3]
param3 = 1 # --- Should be [1,2,3]
The problem is that his big brother is not behaving like it. When it loops through the lists, it gets lost in scheme = 2 and puts dissp_scheme = 2 (freezed) when it should be dissp_scheme = 1. I printed out every single variable that goes inside the function replaceAll marked with comments but when I turn on the other calls it mess up everything. Here is the script.
#!/usr/bin/python
import os
import fileinput
import sys
import shutil
import glob
import time
os.chdir(os.getcwd())
# Replaces the input file parameters
def replaceAll(files,searchExp,replaceExp):
for line in fileinput.input(files, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
# Gets a number inside my input file.
def get_parameter(variable,file_name):
f = open(file_name,'r').readlines()
for i in xrange(len(f)):
index = f[i].find(variable)
if index != -1:
pre_found = f[i].split('=')[1]
return pre_found
# Gets the discretization scheme name.
def get_sheme(number):
if number == 1:
return "Simple Centered Scheme"
elif number == 2:
return "Lax-Wendroff Scheme"
elif number == 3:
return "MacCormack Scheme"
elif number == 4:
return "Beam-Warming Scheme"
elif number == 5:
return "Steger-Warming 1st Order Scheme"
elif number == 6:
return "Steger-Warming 2nd Order Scheme"
elif number == 7:
return "Van Leer 1st Order Scheme"
elif number == 8:
return "Van Leer 2nd Order Scheme"
elif number == 9:
return "Roe Scheme"
elif number == 10:
return "AUSM Scheme"
# Gets the dissipation scheme name.
def get_dissip(number):
if number == 1:
return "Pullian Non-Linear dissipation"
elif number == 2:
return "Second difference dissipation"
elif number == 3:
return "Fourth difference dissipation"
elif number == 4:
return "B&W dissipation"
# Generates the density gnuplot scripts.
def gnuplot(variable,pressure_ratio,scheme,dissip_scheme):
#gnuplot('Density',10,get_sheme(3),'Pullian')
# Building name of the output file.
outFileName = variable.lower() + '_ratio' + str(int(pressure_ratio)) + '_' + scheme.replace(" ","") + '_dissp' + dissip_scheme.replace(" ","") + '.tex'
gnuFileName = variable.lower() + '_ratio' + str(int(pressure_ratio)) + '_' + scheme.replace(" ","") + '_dissp' + dissip_scheme.replace(" ","") + '.gnu'
# Build title of the plot
title = 'Analytical vs Numerical | ' + scheme
f = open(gnuFileName,'w')
f.write("set term cairolatex monochrome size 15.0cm, 8cm\n")
f.write('set output "' + outFileName + '"\n')
f.write("set grid\n")
f.write('set xtics font "Times-Roman, 10\n')
f.write('set ytics font "Times-Roman, 10\n')
f.write('set xlabel "x position" center\n')
f.write('set ylabel "' + variable + '" center\n')
f.write('set title "Analytical vs Numerical Results | ' + variable + '" \n')
f.write('set pointsize 0.5\n')
f.write('set key font ",10"\n')
fortran_out_analytical = 'a' + variable.lower() + '.out'
fortran_out_numerical = variable.lower() + 'Output.out'
f.write('plot "' + fortran_out_analytical +'" u 1:2 with linespoints lt -1 lw 1 pt 4 title "Analytical",\\\n')
f.write( '"' + fortran_out_numerical + '" u 1:2 with lines lw 5 title "Numerical"\n')
f.close()
# Generate latex code.
def generate_latex(text_image_file,caption):
latex.write("\\begin{figure}[H]\n")
latex.write(" \centering\n")
latex.write(" \input{" + text_image_file + "}\n")
latex.write(" \caption{"+ caption +"}\n")
latex.write(" \label{fig:digraph}\n")
latex.write("\\end{figure}\n")
latex.write("\n\n")
# -----------------------------------------------------------------------
# Main loop.
# -----------------------------------------------------------------------
pressure_ratios = [5.0]
schemes = [1,2,3]
dissips = [1,2,3]
# Define replace lines for replace all.
scheme_line = "scheme = "
dissip_line = "dissp_scheme = "
# Open Latex export file.
latex = open("bizu.txt",'w')
i = 0
# ratios.
for i in xrange(len(pressure_ratios)):
print "----------------------------------------"
print " + Configuring File for pressure ratio: " + str(pressure_ratios[i])
print "----------------------------------------\n"
# Schemes
for jj in xrange(len(schemes)):
print " + Configuring file for scheme: " + get_sheme(schemes[jj]) + "\n"
for kkk in xrange(len(dissips)):
print " + Configuring file for dissip: " + get_dissip(dissips[kkk])
# We always work with a brand new file.
os.system("rm input.in")
os.system("cp -a cold.in input.in")
# Replace pressures.
p1_line_old = 'p1 = 5.0d0'
rho1_line_old = 'rho1 = 5.0d0'
p1_line_new = 'p1 = ' + str(pressure_ratios[i]) + 'd0'
rho1_line_new = 'rho1 = ' + str(pressure_ratios[i]) + 'd0'
replaceAll('input.in',p1_line_old,p1_line_new)
replaceAll('input.in',rho1_line_old,rho1_line_new)
# Replace discretization scheme.
old_scheme = scheme_line + "1"
new_scheme = scheme_line + str(schemes[jj])
#==========================================================
# This call is messing everything up when scheme turns to 2
#==========================================================
replaceAll('input.in',old_scheme,new_scheme)
# Replace dissipation scheme.
old_dissp_scheme = dissip_line + "1"
new_dissp_scheme = dissip_line + str(dissips[kkk])
print p1_line_old
print new_scheme
print new_dissp_scheme
replaceAll('input.in',old_dissp_scheme, new_dissp_scheme)
time.sleep(3)
# ### Calling program
# os.system("./sod")
#
latex.close()
And the input file that the it works on is:
&PAR_physical
p1 = 5.0d0
p4 = 1.0d0
rho1 = 5.0d0
rho4 = 1.0d0
fgamma = 1.4d0
R_const = 287.0d0
F_Cp = 1004.5
F_Cv = 717.5
/
&PAR_geometry
total_mesh_points = 1001
start_mesh_point = -5.0d0
final_mesh_point = 5.0d0
print_step = 100
/
&PAR_numeric
scheme = 3
iterations = 10000
time_step = 0.0001d0
/
&PAR_dissip
dissp_scheme = 3
dissip_omega = 0.5d0
/
Thank you all !

Why time() below 0.25 skips animation in Python?

This code works as expected. Output:
Loading
Loading.
Loading..
Loading...
Code:
done = False
count = 0
while not done:
print '{0}\r'.format("Loading"),
time.sleep(0.25)
print '{0}\r'.format("Loading."),
time.sleep(0.25)
print '{0}\r'.format("Loading.."),
time.sleep(0.25)
print '{0}\r'.format("Loading..."),
time.sleep(0.25)
count += 1
if count == 5:
done = True
And this code doesn't. Output:
Loading.
Loading...
Code:
done = False
count = 0
while not done:
print '{0}\r'.format("Loading"),
time.sleep(0.125)
print '{0}\r'.format("Loading."),
time.sleep(0.125)
print '{0}\r'.format("Loading.."),
time.sleep(0.125)
print '{0}\r'.format("Loading..."),
time.sleep(0.125)
count += 1
if count == 5:
done = True
Why does the time function seem to skip every second print statement if it is lower than 0.25?
Reason
Depending on the platform, Python buffers the output to different degrees.
For example, on Mac OSX there is no output at all even for your version with 0.25 seconds sleep.
Flushing manually
Flushing manually should work:
import sys
import time
done = False
count = 0
while not done:
for n in range(4):
print '{0}\r'.format("Loading" + n * '.'),
sys.stdout.flush()
time.sleep(0.125)
print ' ' * 20 + '\r',
count += 1
if count == 5:
done = True
You need to flush the output with sys.stdout.flush(). You also need to print empty spaces to make the dots "going back and forth":
print ' ' * 20 + '\r',
More minimal and cleaned up
This is shortened and a bit more general in terms of the shown text:
import sys
import time
text = 'Loading'
for _ in range(5):
for n in range(4):
print '{0}\r'.format(text + n * '.'),
sys.stdout.flush()
time.sleep(0.25)
nspaces = len(text) + n
print ' ' * nspaces + '\r',
Running unbuffered from the commandline
You can remove the line:
sys.stdout.flush()
if you run your script with the -u option:
python -u script_name.py
Note: This will have an effect on all print statements.

Categories

Resources