2012-07-12 51 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