Python文件输出中加入奇怪的字符

问题描述 投票:0回答:2

原来是我的C程序出错了。我把我的printf改成只打印一个预设的字符串,并把它重定向到一个文件,但多余的字符还是在那里。不过我还是不知道为什么。

你好,我在写一个python脚本,对我做的C程序进行并行分析。写现在我有使用的处理器数量和迭代,我想传递给我的C程序在一个单独的文件称为测试。我对Python极度陌生,这里是我写的示例代码,我想弄清楚如何将结果写到一个文件中,这个文件最终填充为一个.csv文件。

#!/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()

我现在的问题是,当我 "打印结果 "到stdout时,输出结果如预期的那样,我得到3.14blablablablaw什么的。当我检查analysis.txt文件时,在我的pi计算显示出来之前,我在每一行的开头都得到了[H[2J(奇怪的字符,编码为ESC,而不是在网上)。我不明白为什么会这样。为什么 file.write 和 print 的输出不同。同样,这是我第一次使用 Python,所以我可能只是错过了一些简单的东西。

顺便说一下,这是在我用sshing连接的ubuntu服务器上进行的。

下面是test.txt和一张在linux上字符的图片。characters and test

python c linux file-io stdout
2个回答
0
投票

问题是我有一个bash脚本执行我的C程序。bash脚本在程序输出前插入了奇怪的字符,并将其添加到标准输出中。把我调用的命令直接放在python脚本里面,而不是调用bash脚本,就解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.