2014-07-10 28 views
1

我开始使用python,我创建了一个脚本,它将运行valgrind和文件夹中的所有binairies,捕获输出并在需要检查结果时创建文本文件。我的问题是,我得到的输出,但是当我打印它或写入一个新的文件,\ n字符不解释和显示像两个charactere,而不是他们应该换行符。Python创建没有换行符的文本文件

我怎么赶输出

proc.append(subprocess.Popen(
     ['valgrind','--track-origins=yes','--leak-check=full',''.join(['./',files[i]])], 
     stdout=subprocess.PIPE, 
     stderr=subprocess.STDOUT, 
     universal_newlines=True, 
     shell=False, 
     )) 
    print '--> valgrind on', files[i] 
    stdout_value.append(proc[j].communicate()) 

我如何写一个新的文件

 file = open(''.join([os.getcwd(),'/valgrind_output_dir/',result4.group(1),'_output.txt']), "w") 
    file.write(str(stdout_value[i])) 

感谢告诉我什么,我做错了!

+1

删除'STR()''从文件。写',所以它的'file.write(stdout_value [i])' –

+0

哪个操作系统?您是否尝试以二进制模式打开结果文件? – guidot

+0

@BurhanKhalid我有这个错误信息,如果我这样做:file.write(stdout_value [i]) TypeError:期望一个字符缓冲区对象 – MelvinFrohike42

回答

0

尝试这一个:

import subprocess 
with open("file", "wb") as new_file: 
    proc = [] 
    proc.append(subprocess.Popen(
      ["ls", "-l"], 
      stdout=subprocess.PIPE, 
      stderr=subprocess.STDOUT, 
      universal_newlines=True, 
      shell=False, 
      )) 
    new_file.write(proc[0].communicate()[0]) 

问题可能是:PROC [0] .communicate()=>(TEXT,NONE)

Popen.communicate(input=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdoutdata, stderrdata).

+0

很抱歉,但我不明白你要我做 – MelvinFrohike42

+0

我只是说什么: 相反的: file.write (str(stdout_value [i])) 使用: file.write(stdout_value [i] [0]) –

+0

谢谢它的工作!好吧,我明白我只是写从元组的标准输出,而不是像我之前做的整个元组。 – MelvinFrohike42