Python Forum

Full Version: String output displaying \n instead of new line...
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have java class "Test" that returns 2 lines of string output like this:

18 0
1 1 0 0


when i call the java class with python and have python return the output, it returns it like this:

b'18 0\r\n1 1 0 0'

the python 'test_function' function is doing something like this:

process = Popen(['java', 'Test', '-f=' + file], stdout=PIPE)
(stdout, stderr) = process.communicate()

return stdout.strip()

and the main process is calling 'test_function' like this:

print(test_function(arguments))

this is latest version of python...

any ideas how to fix it to where python returns output in same format as java (ie new lines instead of \r \n etc...)
Can you provide a 5-10 line snippet that can easily reproduce the problem?
Yes, here is my JAVA file which displays fine when i run it in JAVA:

public class Test {
public static void main(String[] args) {

System.out.println("18 0");
System.out.println("1 1 0 0");
}
}

_____________________________________________

when i run "py TEST.py" from the command prompt, however, with the below TEST.py file, it gives me the bad output:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
from subprocess import Popen, PIPE

def printData():

process = Popen(['java', 'Test'], stdout=PIPE)
(stdout, stderr) = process.communicate()

return stdout.strip()

print(printData())

I need it to display just as the JAVA displays when i run it (ie new lines instead of \r\n and without a b' in front
It's returning a bytes object, instead of a string.  So to get rid of the b-qualifier, call .decode().

Try this:
(stdout, stderr) = process.communicate()
for line in stdout.strip().decode().splitlines():
    print(line)
The b indicates that it's a binary string. If you want to use it as a normal string, you need to decode it. Try:

print(printData().decode())
Edit: ninja'd