首页 > 解决方案 > 如何在python中使用回车符(\r)和换行符(\n)

问题描述

我正在尝试在 Python 中创建一条随时间变化的消息。我知道我将不得不使用回车来覆盖消息。我想打印以下消息:

It has been (n) minutes since you ran this

Time started: (date when program started)

Time: (date now)

但是当我尝试打印它时,我得到了这个:

It has been 1 minute(s) since the past iteration. Since then, some pretty amazing stuff happened, like:
TIME STARTED: Tue Oct 27 2020, 11:14:41 PM
It has been 2 minute(s) since the past iteration. Since then, some pretty amazing stuff happened, like:
TIME STARTED: Tue Oct 27 2020, 11:14:41 PM

这是我的代码:

import psutil     #psutil - https://github.com/giampaolo/psutil
import time
import sys
import datetime

execute_shell_or_command = sys.executable
found_executable = False

executable_to_find = 'DragonManiaLegends.exe'
iteration = 1
then = time.time()

# Get a list of all running processes
while not found_executable:
    list = psutil.pids()

    # Go though list and check each processes executeable name for 'putty.exe'
    for i in range(0, len(list)):
        try:
            p = psutil.Process(list[i])
            if p.cmdline()[0].find(executable_to_find) != -1:
                # DML found. Kill it
                now = time.time()
                print(f"Found {executable_to_find}. Killing execution...")
                p.kill()
                datetime_str_now = datetime.datetime.fromtimestamp(now).strftime('%a %b %d %Y, %I:%M:%S %p')
                datetime_str_then = datetime.datetime.fromtimestamp(then).strftime('%a %b %d %Y, %I:%M:%S %p')
                print(f"On {datetime_str_then}, you have started your quest to  t e r m i n a t e  {executable_to_find}"
                      f"\nOn {datetime_str_now}, you have completed that quest, and it has been terminated."
                      f"\nIt only took you {round(now - then)} seconds to elimate {executable_to_find}!")
                # found_executable = True  # Comment this out to loop FOREVER
                # break
        except:
            pass

    if 'python.exe' in execute_shell_or_command:
        now = time.time()
        datetime_str_now = datetime.datetime.fromtimestamp(now).strftime('%a %b %d %Y, %I:%M:%S %p')
        datetime_str_then = datetime.datetime.fromtimestamp(then).strftime('%a %b %d %Y, %I:%M:%S %p')
        sys.stdout.write(f"\rIt has been {iteration} minute(s) since the past iteration. Since then, some pretty amazing stuff happened, like:\nTIME STARTED: {datetime_str_then}.\nTIME: {datetime_str_now}")
        sys.stdout.flush()
        #  print(f"\rIt has been {iteration} minute(s) since the past iteration. Since then, some pretty amazing stuff happened, like: TIME STARTED: {datetime_str_then}. TIME: {datetime_str_now}", end="", flush=True)
        iteration += 1
    
    time.sleep(60)

PS 我正在使用 Window 的命令提示符来运行代码

标签: python

解决方案


尝试使用两个\n,因为一个只会插入一个换行符,另一个会显示一个空行:

sys.stdout.write(f"\rIt has been {iteration} minute(s) since the past iteration. Since then, some pretty amazing stuff happened, like:\n\nTIME STARTED: {datetime_str_then}.\n\nTIME: {datetime_str_now}")

推荐阅读