En python 3, podemos imprimir fácilmente en la misma línea usando el siguiente script. Lo uso para comprender el progreso de mi bucle (cuánto tiempo me quedará). Sin embargo, en jupyter no funciona (imprime en diferentes líneas)
import time for f in range(10): print(f, end='\r', flush=True) time.sleep(10)No funciona para desactivar la impresión bonita %pprint, y probé lo mismo con sys.stdout.write() pero también tengo este problema.
Encontré la solución a esto un poco más tarde (tenga en cuenta que no funciona en pycharm jupyter, sino solo en la implementación del navegador). Para mí, print funciona bien, pero aquí se recomienda display , pero imprime apóstrofes alrededor de las cadenas.
from time import sleep from IPython.display import clear_output, display for f in range(10): clear_output(wait=True) print(f) # use display(f) if you encounter performance issues sleep(10)Editar: solo quería agregar que TQDM a menudo también es una buena herramienta para este objetivo. Muestra barras de progreso y le permite escribir resultados debajo o diferenciar la descripción de cada barra. Véase también esta publicación .
import sys from tqdm import tqdm from time import sleep values = range(3) with tqdm(total=len(values), file=sys.stdout) as pbar: for i in values: pbar.set_description('processed: %d' % (1 + i)) pbar.update(1) sleep(1)Y el de la libreta con lindos colores
from tqdm import tqdm, tqdm_notebook from time import sleep for i in tqdm_notebook(range(2), desc='1st loop'): sleep(0.01) tqdm.write(f"Done task {i}")Prefije un \r y agregue un argumento end="" para imprimir, así
print("\rThis will be printed on the same line", end="")
Esto funciona en el cuaderno Jupyter en Google Colab.
La parte "\r" sobrescribe la línea, si la dejas, la agregas a la línea. Su versión print(f, end='', flush=False) podría funcionar, pero he leído en Python 3 que necesita usar sys.stdout.write() y lo mejor es si también agrega el comando de descarga.
import sys import time for f in range(10): #delete "\r" to append instead of overwrite sys.stdout.write("\r" + str(f)) sys.stdout.flush() time.sleep(10)Se requiere stdout.flush en algunos sistemas o no obtendrá ningún resultado