2013-02-16 70 views
1

我需要爲Windows編寫代碼,該代碼將運行一個exe調用foil2w.exe,該調用可以從機翼進行一些空氣動力學計算。這exe有一個輸入文本文件(dfile_bl)與很多變量。然後在每次運行後,我必須打開它,將值(迎角)從0更改爲16,然後再次運行。還會生成一個名爲aerola.dat的輸出文件,我必須保存最後一行,該行最後一行是結果。 我想要做的是自動化過程,運行程序,保存結果改變角度並再次運行。我已經完成了Linux的操作,並使用sed命令來查找和更換角度線。現在我必須爲Windows做這件事,我不知道如何開始。我對Linux所做的代碼,它工作正常:替換文本文件中的特定行

import subprocess 
import os 

input_file = 'dfile_bl' 
output_file = 'aerloa.dat' 
results_file = 'results.txt' 

try: 
    os.remove(output_file) 
    os.remove(results_file) 
except OSError: 
    pass 

for i in [0, 2, 4, 6, 8, 10, 12, 14, 16]: 
    subprocess.call('./exe', shell=True) 
    f = open(output_file, 'r').readlines()[-1] 
    r = open(results_file, 'a') 
    r.write(f) 
    r.close() 
    subprocess.call('sed -i "s/%s.00  ! ANGL/%s.00  ! ANGL/g" %s' % (i, i+2, input_file), shell=True) 

subprocess.call('sed -i "s/18.00  ! ANGL/0.00  ! ANGL/g" %s' % input_file, shell=True) 

的dfile樣子:

3.0   ! IFOIL 
n2412aN  
0.00  ! ANGL 
1.0  ! UINF 
300  ! NTIMEM 

編輯: 現在是工作的罰款

import subprocess 
import os 
import platform 

input_file = 'dfile_bl' 
output_file = 'aerloa.dat' 
results_file = 'results.txt' 
OS = platform.system() 
if OS == 'Windows': 
    exe = 'foil2w.exe' 
elif OS == 'Linux': 
    exe = './exe' 

try: 
    os.remove(output_file) 
    os.remove(results_file) 
except OSError: 
    pass 

for i in [0, 2, 4, 6, 8, 10, 12, 14, 16]: 
    subprocess.call(exe, shell=OS == 'Linux') 
    f = open(output_file, 'r').readlines()[-1] 
    r = open(results_file, 'a') 
    r.write(f) 
    r.close() 
    s = open(input_file).read() 
    s = s.replace('%s.00  ! ANGL' % str(i), '%s.00  ! ANGL' % str(i+2)) 
    s2 = open(input_file, 'w') 
    s2.write(s) 
    s2.close() 
# Volver el angulo de dfile_bl a 0 
s = open(input_file).read() 
s = s.replace('%s.00  ! ANGL' % str(i+2), '0.00  ! ANGL') 
s2 = open(input_file, 'w') 
s2.write(s) 
s2.close() 
b 
+0

偉大創舉,自動執行此! – slezica 2013-02-16 18:32:07

+0

@uʍopǝpısdn和一個更好的問題比http://stackoverflow.com/questions/14901383/python-replce-a-specific-line-in-text-file - 但仍需要澄清從我原來的評論是更廣泛的使用;) – 2013-02-16 18:32:58

+0

你能告訴我們'dbfile_bl'的提取嗎?這可能有助於瞭解你想要做的事情。 – 2013-02-16 18:41:39

回答

0

無法更換

subprocess.call('sed -i "s/%s.00  ! ANGL/%s.00  ! ANGL/g" %s' % (i, i+2, input_file), shell=True) 

喜歡的東西,

with open('input_file', 'r') as input_file_o: 
    for line in input_file_o.readlines(): 
     outputline = line.replace('%s.00  ! ANGL' % i, '%s.00  ! ANGL' % i+2) 

[1] http://docs.python.org/2/library/stdtypes.html#str.replace

+0

哇,你快,我會試試。 – user1181237 2013-02-16 20:37:26

+0

我嘗試了你的解決方案,我得到了這個'Traceback(最近調用最後一個): 文件「run2.py」,第20行,在 中input_file.readlines()中的行: AttributeError:' str'對象沒有屬性'readlines'' – user1181237 2013-02-16 23:32:24

+0

是的,'input_file'必須是文件對象,我沒有讓這段代碼100%正確,只是爲了給你一個想法...我會編輯示例來反映這一點。 .. – f13o 2013-02-17 10:05:01