J. C.
J. C.

Reputation: 109

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. 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?

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)

Upvotes: 2

Views: 10487

Answers (2)

Patrick the Cat
Patrick the Cat

Reputation: 2168

You can write to stdout directly:

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.

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.

Upvotes: 3

Emmanuel Mtali
Emmanuel Mtali

Reputation: 4983

Use

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

Or

print(output_line.rstrip())

Upvotes: 2

Related Questions