2012-07-12 49 views
0

我正在编写一个测试脚本,它只需运行带有几个参数的* .EXE文件,然后将结果输出到文件。我有一个正确运行测试的* .sh测试脚本(但需要手动更新以进行更多测试)。在这个脚本的线条看起来像这样:Python输出CR CR LF?

blah.exe arg1 arg2 arg3 > ../test/arg4/arg4.out 

我写了一个python脚本自动生成基于几个简单的Python模块的参数(这是很粗糙现在):

import os 
import subprocess 

for test_dir in os.listdir(): 
    if not os.path.isdir(test_dir): 
     continue 
    # load a few variables from the ./test_dir/test_dir.py module 
    test_module = getattr(__import__(test_dir, fromlist=[test_dir]), test_dir) 

    # These arguments are relative paths, fix the paths 
    arg1 = os.path.join(test_dir, test_module.ARG1) 
    arg2 = os.path.join(test_dir, test_module.ARG2) 
    arg3 = os.path.join(test_dir, test_module.ARG3) 

    proc = subprocess.Popen(["../bin/blah.exe", arg1, arg2, arg3], stdout=subprocess.PIPE) 

    stdout_txt = proc.stdout.read().decode("utf-8") 

    with open(os.path.join(test_dir, test_dir + '.out'), 'w') as f: 
     f.write(stdout_txt) 

我已经打开文件进行比较,而脚本正在工作,我遇到了一个问题。第一种(外壳)解决方案输出正确的行结束符。第二个(python)解决方案输出以CR CR LF结尾的行。这看起来是正确的在记事本中,但在记事本++,每隔一行显示为空白:

These lines should have no empty lines between them

为什么蟒蛇给予不当行结束输出?

如何纠正行尾?(将CR CR LF更改为CR LF而不必编写其他脚本)

回答

2

尝试使用universal_newlines=True参数Popen(请参阅http://docs.python.org/library/subprocess.html#popen-constructor)。

+0

哇,这是一个简单的修复,谢谢!我想知道为什么这不是默认启用的(只要足够的时间过去了,就会接受)。 – Darthfett 2012-07-12 18:22:57

+0

@Darthfett:它不是使用您所看到的换行符的Python,并且不以任何方式混淆进程输出的默认行为对我来说似乎是合理的。 – geoffspear 2012-07-12 18:35:44

+0

@Wooble啊,我不知道这里发生了什么。谢谢!如果这是真的,那么因为我已经继承了.EXE的源代码,我想这意味着我可能有一些工作要做。 – Darthfett 2012-07-12 19:01:38