简体   繁体   中英

Python file output adding weird characters

Turns out it is an error with my C program. I changed my printf to only print a preset string and redirected it to a file and the extra characters were still there. I still don't know why though.

Hi I'm writing a python script to run analysis on a C program I'm making parallel. Write now I have the number of processors used and the iterations I want to pass to my C program in a separate file called tests. I'm extremely new to Python, here's my sample code I wrote to figure out how to write results to a file which fill eventually be a .csv file.

#!/usr/bin/env python
import subprocess
mpiProcess = "runmpi"
piProcess = "picalc"

tests = open("tests.txt")
analysis = open("analysis.txt", "w")

def runPiCalc (numProcs, numIterations):
    numProcs = str(numProcs)
    numIterations = str(numIterations)
    args = (mpiProcess, piProcess, numProcs, numIterations)
    popen = subprocess.Popen(args, stdout=subprocess.PIPE)
    popen.wait()
    output = popen.stdout.read()
    return output

def runTest (testArgs):
    testProcs = testArgs[0]
    testIterations = testArgs[1]
    output = runPiCalc(testProcs,testIterations)
    appendResults(output)

def appendResults (results):
    print results
    analysis.write(results + '\n')

for testLine in tests:
    testArgs = testLine.split()
    runTest(testArgs)

tests.close()
analysis.close()

My problem right now is when I "print results" to stdout the output comes out as expected and I get 3.14blablablablawhatever. When I check the analysis.txt file though I get [H[2J (weirder characters that are encoded as ESC not on the web) at the start of every line before my pi calculation shows up. I can't figure out why that is. Why would file.write have different output than print. Again this is my first time with Python so I'm probably just missing something easy.

This is on a ubuntu server I'm sshing to btw.

Here's the tests.txt and a picture of how the characters look on linux字符和测试

The problem was I had a bash script executing my C program. The bash script was inserting the weird characters before the program output and adding it to its standard output. Putting the command I was calling inside the python script directly instead of calling a bash script fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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