2013-02-16 72 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