从另一个python文件编辑python文件中的参数

2024-05-16 18:47:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经得到了一个应用程序的配置文件,它是一个python文件,包含一个dict,我正在运行一个AWS lambda函数,从S3获取这个conf文件,更改其中的三个变量,然后将一个副本推回到S3。有什么简单的方法吗?一位同事说要尝试Jinja模板,但似乎仅限于HTML文件

谢谢

python配置文件的示例如下。我需要改变“alpha”和“cycles”变量

import zutil alpha = 2.13 cycles = 100 def my_transform(x, y, z): v = [x, y, z] v = zutil.rotate_vector(v, alpha, 0.0) return {'v1': v[0], 'v2': v[1], 'v3': v[2]} parameters = { # units for dimensional quantities 'units': 'SI', # reference state 'reference': 'IC_1', 'time marching': { 'unsteady': { 'total time': 1.0, 'time step': 1.0, 'order': 'second', }, 'scheme': { 'name': 'lu-sgs', 'stage': 1, #'name' : 'runge kutta', #'stage': 5, }, 'lu-sgs': { 'Number Of SGS Cycles': 8, 'Min CFL': 0.1, 'Max CFL': 5.0, 'Include Backward Sweep': True, 'Include Relaxation': True, 'Jacobian Update Frequency': 1, 'Jacobian Epsilon': 1.0e-08, 'CFL growth': 1.05, 'Use Rusanov Flux For Jacobian': 'true', 'Finite Difference Jacobian': 'false', }, 'multigrid': 10, 'cfl': 2.5, 'cfl transport': 2.5 * 0.5, 'ramp': {'initial': 1.0, 'growth': 1.1}, 'cycles': cycles, }, 'equations': 'RANS', 'RANS': { 'order': 'euler_second', 'limiter': 'vanalbada', 'precondition': 'true', 'turbulence': { 'model': 'sst', }, }, 'material': 'air', 'air': { 'gamma': 1.4, 'gas constant': 287.0, 'Sutherlands const': 110.4, 'Prandtl No': 0.72, 'Turbulent Prandtl No': 0.9, }, 'IC_1': { 'temperature': 310.928, 'pressure': 101325.0, 'alpha': alpha, # User defined variable used for post processing 'V': { 'vector': zutil.vector_from_angle(alpha, 0.0), 'Mach': 0.85, }, 'Reynolds No': 5.0e6, 'Reference Length': 275.8, 'turbulence intensity': 1.e-4, 'eddy viscosity ratio': 0.1, }, 'BC_1': { 'ref': 7, 'type': 'symmetry', }, 'BC_2': { 'ref': 3, 'type': 'wall', 'kind': 'noslip', }, 'BC_3': { 'ref': 9, 'type': 'farfield', 'condition': 'IC_1', 'kind': 'riemann', }, 'write output': { 'format': 'vtk', 'surface variables': ['V', 'p', 'T', 'rho', 'walldist', 'yplus', 'mach', 'cp', 'eddy', 'pressureforce', 'frictionforce'], 'volume variables': ['V', 'p', 'T', 'rho', 'walldist', 'mach', 'cp', 'eddy'], 'frequency': 500, }, 'report': { 'frequency': 10, 'forces': { 'FR_1': { 'name': 'wall', 'zone': [9, 10, 11, 12, 13], 'transform': my_transform, 'reference area': 594720.0 * 0.5, # half model area # half model area # half model area }, }, }, }

Tags: 文件nonamealphamodeltimetransformarea
2条回答

Jinja2当然可以做到。但是否值得做是另一个问题

我对你的文件做了一点修改,使它可以被jinja2渲染

import zutil

alpha = {{ alpha | default(2.13) }}
cycles = {{ cycles | default(100)}}

def my_transform(x,y,z):
    v = [x,y,z]
    v =  zutil.rotate_vector(v,alpha,0.0)
    return {'v1' : v[0], 'v2' : v[1], 'v3' : v[2]}

parameters = { 

 # units for dimensional quantities
'units' : 'SI',

# reference state
'reference' : 'IC_1',

'time marching' : { 
                   'unsteady' : {
                                 'total time' : 1.0,
                                 'time step' : 1.0,
                                 'order' : 'second',
                                },
                   'scheme' : {
                             'name' : 'lu-sgs',
                               'stage': 1,
                               #'name' : 'runge kutta',
                               #'stage': 5,
                               },
                   'lu-sgs' : {
                               'Number Of SGS Cycles' : 8,
                               'Min CFL' : 0.1,
                               'Max CFL' : 5.0,
                               'Include Backward Sweep' : True,
                               'Include Relaxation' : True,
                               'Jacobian Update Frequency' : 1,
                               'Jacobian Epsilon' : 1.0e-08,
                               'CFL growth' : 1.05,
                               'Use Rusanov Flux For Jacobian' : 'true',
                               'Finite Difference Jacobian' : 'false',
                              },

                   'multigrid' : 10,
                   'cfl': 2.5,
                   'cfl transport' : 2.5*0.5,
                   'ramp': { 'initial': 1.0, 'growth': 1.1 },
                   'cycles' : cycles,
                  },

'equations' : 'RANS',

'RANS' : {
               'order' : 'euler_second',
               'limiter' : 'vanalbada',
               'precondition' : 'true',                                          
               'turbulence' : {
                               'model' : 'sst',
                              },
               },

'material' : 'air',
'air' : {
        'gamma' : 1.4,
        'gas constant' : 287.0,
        'Sutherlands const': 110.4,
        'Prandtl No' : 0.72,
        'Turbulent Prandtl No' : 0.9,
        },
'IC_1' : {
          'temperature':310.928,
          'pressure':101325.0,
          'alpha': alpha, # User defined variable used for post processing
          'V': {
                'vector' : zutil.vector_from_angle(alpha,0.0),
                'Mach' : 0.85,
                },
           'Reynolds No' : 5.0e6,
           'Reference Length' : 275.8, 
          'turbulence intensity':1.e-4,
          'eddy viscosity ratio':0.1,
          },
'BC_1' : {
          'ref' : 7,
          'type' : 'symmetry',
         },
'BC_2' : {
          'ref' : 3,
          'type' : 'wall',
          'kind' : 'noslip',
         },
'BC_3' : {
          'ref' : 9,
          'type' : 'farfield',
          'condition' : 'IC_1',
          'kind' : 'riemann',
         },
'write output' : {
                  'format' : 'vtk',
                  'surface variables': ['V','p','T','rho','walldist','yplus','mach','cp','eddy','pressureforce','frictionforce'],
                  'volume variables': ['V','p','T','rho','walldist','mach','cp','eddy'],
                  'frequency' : 500,
                 },      
'report' : {
           'frequency' : 10,
        'forces' : {
            'FR_1' : {
                'name' : 'wall',
                'zone' : [9,10,11,12,13],
                'transform' : my_transform,
                'reference area' : 594720.0*0.5, # half model area # half model area # half model area 
            },
        },
},                      
}

下面是如何使用jinja2渲染它。假设路径\1是配置文件的路径。路径2是新配置文件的路径

from jinja2 import Environment, FileSystemLoader

new_config_contex = {'alpha':3, 'cycles': 200}
path, template_filename = os.path.split(path_1)
env = Environment(loader=FileSystemLoader(path))
new_conf_file_content=env.get_template(template_filename).render(new_config_contex)
with open(path_2, "wb") as f:
    f.write(new_conf_file_content)

我找到了一个解决方案,它并不漂亮,正如SRC提到的,它是一个不好的解决方案,不应该用在任何真实的东西上,但它是有效的

我听取了milo的建议,并将reference control.py文件转换为Jinja模板,如下所示:

import jinja2 from sys import argv pyConf = """ import zutil alpha = {{alpha}} cycles = {{cycles}} def my_transform(x,y,z): v = [x,y,z] v = zutil.rotate_vector(v,alpha,0.0) return {'v1' : v[0], 'v2' : v[1], 'v3' : v[2]} parameters = { # units for dimensional quantities 'units' : 'SI', # reference state 'reference' : 'IC_1', 'time marching' : { 'unsteady' : { 'total time' : 1.0, 'time step' : 1.0, 'order' : 'second', }, 'scheme' : { 'name' : 'lu-sgs', 'stage': 1, #'name' : 'runge kutta', #'stage': 5, }, 'lu-sgs' : { 'Number Of SGS Cycles' : 8, 'Min CFL' : 0.1, 'Max CFL' : 5.0, 'Include Backward Sweep' : True, 'Include Relaxation' : True, 'Jacobian Update Frequency' : 1, 'Jacobian Epsilon' : 1.0e-08, 'CFL growth' : 1.05, 'Use Rusanov Flux For Jacobian' : 'true', 'Finite Difference Jacobian' : 'false', }, 'multigrid' : 10, 'cfl': 2.5, 'cfl transport' : 2.5*0.5, 'ramp': { 'initial': 1.0, 'growth': 1.1 }, 'cycles' : cycles, }, 'equations' : 'RANS', 'RANS' : { 'order' : 'euler_second', 'limiter' : 'vanalbada', 'precondition' : 'true', 'turbulence' : { 'model' : 'sst', }, }, 'material' : 'air', 'air' : { 'gamma' : 1.4, 'gas constant' : 287.0, 'Sutherlands const': 110.4, 'Prandtl No' : 0.72, 'Turbulent Prandtl No' : 0.9, }, 'IC_1' : { 'temperature':310.928, 'pressure':101325.0, 'alpha': alpha, # User defined variable used for post processing 'V': { 'vector' : zutil.vector_from_angle(alpha,0.0), 'Mach' : 0.85, }, 'Reynolds No' : 5.0e6, 'Reference Length' : 275.8, 'turbulence intensity':1.e-4, 'eddy viscosity ratio':0.1, }, 'BC_1' : { 'ref' : 7, 'type' : 'symmetry', }, 'BC_2' : { 'ref' : 3, 'type' : 'wall', 'kind' : 'noslip', }, 'BC_3' : { 'ref' : 9, 'type' : 'farfield', 'condition' : 'IC_1', 'kind' : 'riemann', }, 'write output' : { 'format' : 'vtk', 'surface variables': ['V','p','T','rho','walldist','yplus','mach','cp','eddy','pressureforce','frictionforce'], 'volume variables': ['V','p','T','rho','walldist','mach','cp','eddy'], 'frequency' : 500, }, 'report' : { 'frequency' : 10, 'forces' : { 'FR_1' : { 'name' : 'wall', 'zone' : [9,10,11,12,13], 'transform' : my_transform, 'reference area' : 594720.0*0.5, # half model area # half model area # half model area }, }, }, } """ template = jinja2.Template(pyConf) print template.render(alpha = argv[1], cycles = argv[2])

然后我修改了lambda函数,得到这个模板,执行它,它将现在呈现的控制文件打印到stdio,在lambda函数中,我为exec函数重定向了stdio,在那里我可以捕获它并将它流到一个S3对象中,然后将它推回到S3

找到了重定向stdiohere的想法

为了扩展,我将通过stdin传递lambda函数作为jinja模板的参数

相关问题 更多 >