简体   繁体   English

Python如何不打印\\ r和\\ n

[英]Python how to not print \r and \n

I have this code that runs a minecraft server from python and prints everything in the command line. 我有这段代码从python运行minecraft服务器,并在命令行中打印所有内容。 However, at the end of every line it prints "\\r\\n" and I don't want it to, is there any way to get rid of it? 但是,在每一行的末尾都显示“ \\ 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)

You can write to stdout directly: 您可以直接写到stdout:

import sys
sys.stdout.write("Hello world!")
sys.stdout.write(" I'm superman :D")

The above code should print on the same line 上面的代码应该打印在同一行上


As requested, it seems like OP wants to print a long string with line breakers embedded, but don't want the line breakers to be effective. 根据要求,OP似乎想打印一个嵌入了换行器的长字符串,但不希望换行器有效。

Let's say I have a text file that has two lines 假设我有一个包含两行的文本文件

Hey line 1!
I'm line 2.

The following code will print two lines without line breaker, replacing line breakers with spaces: 下面的代码将打印两行而没有换行符,将换行符替换为空格:

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

That is, it will print 也就是说,它将打印

Hey line 1! I'm line 2.

You can also parse the lines, then print each line without line breakers: 您还可以解析行,然后在不使用换行符的情况下打印每行:

for line in f:
     sys.stdout.write(line.strip() + ' ')

Hope this is what you want. 希望这就是你想要的。

Use 采用

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

Or 要么

print(output_line.rstrip())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM