Reputation: 61
Hello i am fairly new to Python and i would like to automate some latex pdf report generation. So i want to make a function that takes x numbers of string variables as input and insert them into a predefined latex text, such that it can be compiled as a report pdf. I really hope that someone can help me with this problem. I have tried doing like shown below, which obviously does not work:
def insertVar(site, turbine, country):
site = str(site)
turbine = str(turbine)
country = str(country)
report = r'''On %(site)s there are 300 %(turbine)s wind turbines, these lies in %(country)s'''
with open('report.tex','w') as f:
f.write(report)
cmd = ['pdflatex', '-interaction', 'nonstopmode', 'report.tex']
proc = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE)
proc.communicate()
retcode = proc.returncode
if not retcode == 0:
os.unlink('report.pdf')
raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd)))
os.unlink('report.tex')
os.unlink('report.log')
insertVar('atsumi', 'ge', 'japan')
So i want the output of the PDF to read: "On atsumi there are 300 ge wind turbines, these lies in japan"
Upvotes: 0
Views: 2823
Reputation: 22472
Try using str.format():
report = "On {} there are 300 {} wind turbines, these lies in {}".format(site, turbine, country)
If you like you can use %
instead, note, however, this is the old style:
report = "On %s there are 300 %s wind turbines, these lies in %s" % (site, turbine, country)
Note: I do not see the need for using a raw string in your case.
Upvotes: 1
Reputation: 274
Here's a start:
report = r'''On %(site)s there are 300 %(turbine)s wind turbines, these lies in %(country)s'''
with open('report.tex','w') as f:
f.write(report)
Should be:
report = r'''On {a}s there are 300 {b}s wind turbines, these lies in {c}s'''.format(a=site, b=turbine, c=country)
with open('report.txt','w') as f:
f.write(report)
Upvotes: 1