Python如何不打印\r和\n

Python如何不打印\r和\n,python,Python,我有一段代码,它从python运行minecraft服务器,并在命令行中打印所有内容。但是,在每一行的末尾,它都会打印“\r\n”,我不希望它这样做,有什么办法可以去掉它吗 import subprocess def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.

我有一段代码,它从python运行minecraft服务器,并在命令行中打印所有内容。但是,在每一行的末尾,它都会打印“\r\n”,我不希望它这样做,有什么办法可以去掉它吗

import subprocess

def run_command(command):
    p = subprocess.Popen(command,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
    return iter(p.stdout.readline, b'')

for output_line in run_command('java -Xmx2048M -Xms2048M -jar minecraft_server.jar nogui'):
    print(output_line)

您可以直接向标准输出写入:

import sys
sys.stdout.write("Hello world!")
sys.stdout.write(" I'm superman :D")
上述代码应打印在同一行上


根据要求,OP似乎希望打印一个嵌入了换行符的长字符串,但不希望换行符有效

假设我有一个文本文件,它有两行

Hey line 1!
I'm line 2.
以下代码将打印两行不带换行符的换行符:

txt = ''
with open('somename.txt', 'r') as f:
    txt = f.read().replace('\r\n', ' ')
    txt = txt.replace('\n\r', ' ')
    txt = txt.replace('\n', ' ')
    txt = txt.replace('\r', ' ')
print txt
也就是说,它将打印

Hey line 1! I'm line 2.
您还可以分析行,然后在不使用换行符的情况下打印每行:

for line in f:
     sys.stdout.write(line.strip() + ' ')
希望这就是你想要的。

使用

print('Minecraft server', end="")


不要忘记
sys.stdout.flush()
我不希望它打印在同一行上,我希望它打印多行,但问题是,它在每行末尾添加了“\r\n”,我不希望that@J.C.我认为\r是recur,而\n是newline。那么,如果在一行的末尾没有它们,会发生什么呢?它来自程序本身。我的代码将服务器控制台(java东西)打印到命令行(python脚本控制台)。例如,这就像将文本文件打印到控制台,并将换行符保留在其中。我只是想让它们不被打印。python 2:print'Minecraft server',#注意尾端的逗号,我假设你是指print(output_line,end=“”),但这不起作用,程序没有打印anything@EmmanuelMtali不,没有。正如我在上面的评论中所说,它没有打印任何内容。你能把它添加到我的代码中并发布吗?我可能做错了
print(output_line.rstrip())