1

I am trying to write a file from a sample template file. I need to replace ONLY $UPPERINTERFACE with interface.

This is the sample template.txt

localparam $UPPERINTERFACE_WDTH = 1;
localparam $UPPERINTERFACE_DPTH = 8;
localparam $UPPERINTERFACE_WTCHD = 2;

This is the code:

from string import Template
intf = "interface"
rdfh = open("template.txt", "r").readlines()
wrfh = open("myfile.txt", "w")
for line in rdfh:
    s = Template(line)
    s = s.substitute(UPPERINTERFACE=intf.upper())
    wrfh.write(s)
rdfh.close()
wrfh.close()

Expected output:

localparam interface_WDTH = 1;
localparam interface_DPTH = 8;
localparam interface_WTCHD = 2;

As it is taking $UPPERINTERFACE_WDTH as a variable to be replaced, I am getting following error:

KeyError: 'UPPERINTERFACE_WDTH'

Is there any way I can replace only $UPPERINTERFACE with interface here?

1 Answer 1

1

You can use curly braces {} to narrow down the template key as in following template string:

>>> line = 'localparam ${UPPERINTERFACE}_WDTH = 1;'
>>> Template(line).substitute(UPPERINTERFACE=intf.upper())
'localparam INTERFACE_WDTH = 1;'

The documentation states the following:

${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "${noun}ification".

Sign up to request clarification or add additional context in comments.

1 Comment

I think you have missed last line of my question. I need to replace ONLY $UPPERINTERFACE with interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.