How can I write a Python script that takes a plain text file littered with placeholders, and then prompts me to replace each placeholder before sending it out to a provided email address?
Essentially, I’m looking to use something similar to 'Replacing text with variables' but I’d like to input the different variables from the terminal like in a simple bash script (rather than defining them in the script). I’d like to begin scripting in Python rather than continuing to write bash scripts; it’s for the best.
Once you have the template with the placeholders, you just need to render it using a dictionary that contains all the variables you need in the template as context. This is the approach used by most of the templating systems.
For example,
value = raw_input('prompt> ')
template = 'This is the {value}'
context = {'value': value}
print template.format(**context)
Related
I am trying for my code to pull a file when only a portion of the file name changes.
Example: I want to pull the file named JEFF_1234.csv where 1234 is an input from a GUI window.
The reason for the file name to have this structure is I want to have one main database that has multiple files for a specific part number. So if the user inputs a part number of 1234 and that will point to 4 files. JEFF_1234.csv, SAM_1234.csv, FRED_1234.csv and JACK_1234.csv.
What you need is a way to update a template with some dynamic value.
A neat way to do this is to define a template string using curly brackets as place-holders for the content that will be generated at runtime.
jefffile_template = "JEFF_{t}.csv"
Then, once you've assigned a value to the unknown pointer, you can convert your template into an appropriate string:
jeff_filename = jefffile_template.format(t="1234")
Which will store the value of JEFF_1234.csv into the variable jeff_filename for usage later in your program.
There are other similar ways of calling formatting functions, but using this by name style is my preferred method.
...and in case you're wondering, yes, this was still valid in 2.7.
Can you please help me is there way to pass formatted string from python file to robot file suppose say below is my specific language py file
English.py file has below variable assigned
FILTERED_TEXT_LANG = "{} Selected"
Robot test cases is setting the variable is like below in robot file (user.robot)
${element} = Set Variable xpath=*//div[contains(#id,'org-selection-counter') and contains(text(),'${FILTERED_TEXT_LANG}.format(some_filtered_count)')]
This is required since different language is displaying the some_filtered_count in different way , is there way can make the changes from string formatted not if else conditions
Well, there's a way, but not like this:
${element} = Set Variable xpath=*//div[contains(#id,'org-selection-counter') and contains(text(),'${FILTERED_TEXT_LANG}.format(some_filtered_count)')]
you can't use Python keywords, methods etc. directly in RF. But what you can do is create your custom keyword, either in RF, or in Python, that you latter use in RF and it will fill in a language into the string. Actually, you don't even need to create anything, just reuse what's already available in String library
I can imagine something like this:
${str_with_language}= Replace String ${FILTERED_TEXT_LANG} {} ENG
${element} = Set Variable xpath=*//div[contains(#id,'org-selection-counter') and contains(text(),'${str_with_language}')]
I'm pretty new to Django and LaTeX so I'm hoping that someone out there has done something like this before:
I'm trying to create a Django app that can read a LaTeX file, extract all of the variables (things of this form: "\newcommand{\StartDate}{January 1, 2018}") and place them as key/value pairs into a dictionary that I can work with inside Django.
The idea is that each variable in the LaTeX file starts with a place holder value. I'll be building a dynamic form that uses the dictionary to create field/values and let's a user replace the place holder value with a real one. After a user has set all of the values, I'd like to be able to write those new values back into the LaTeX file and generate a pdf from it.
I've tried regular expressions but have run into trouble because some of the 'variables' will contain blocks of LaTeX like lists, for example. I've also looked at TexSoup which seems to be very promising but I haven't been able to totally figure out yet. Here is a section from the preamble of an example LaTeX file like the ones I'll be dealing with:
%% Project Name
\newcommand{\projectName}{Project Name}
%% Start and End dates
\newcommand{\startDate}{January 1, 2018}
\newcommand{\finDate}{December 31, 2018}
%% Name of User
\newcommand{\userName}{aUser}
% What tasks will be a part of this process?
\newcommand{\tasks}{
\begin{itemize}[noitemsep,topsep=0pt]
\item Planning of \projectName{} on \startDate{}
\item Construction of \projectName{}
\item Configuration of \projectName{} by \userName{} on \finDate{}
\end{itemize}
}
Using TexSoup, I'm able to pull the LaTex file into an object, find all instances of a '\newcommand' into a generator object that I can iterate:
from TexSoup import TexSoup
soup = TexSoup(open('slatex.tex'))
newcommands = list(soup.find_all('newcommand'))
I know that this is pulling each '\newcommand' into its own element and maintaining the formats properly because I can easily print them out one at a time.
I'm stuck trying to figure out how to pull the '\newcommand' from each item, get the name of the item into a dictionary key and the value into a dictionary value. I'd like to think that TexSoup exposes those with some kind of attribute or method but I can't find anything about it. If it doesn't, am I back to looking at regular expressions again?
Each of the \newcommands has two required arguments, denoted using {}. As a result, we can
access each newcommand's arguments, and
access the value of each argument
With your definition of slatex.tex above, we can obtain
{'\\finDate': 'December 31, 2018', '\\startDate': 'January 1, 2018'}
using the following script
from pprint import pprint
from TexSoup import TexSoup
soup = TexSoup(open('slatex.tex'))
newcommands = list(soup.find_all('newcommand'))
result = {}
for newcommand in newcommands:
key, value = newcommand.args
result[key.value] = value.value
pprint(result)
*On a side note, TexSoup doesn't yet understand that these redefined variables will have tangible impact on the rest of the document. It treats them as any other command, passively.
Maybe this isn't the best way to frame my problem. Right now, I have a program that already uses argparse to enter my class in 'manual' mode. So for example, if I type python parser.py --m, I go to Parse(args), which is my class. This all works fine.
Once this is done, the class parses the file for its table of contents list and prints it to the screen. The table of contents is an OrderedDict with the page number as the key and the page title as the value. The idea is that you could press a number and it would print out the text on that respective page, and that you could do this until you type any command that doesn't correspond to a number in the dict.
I was wondering if this would be possible to do with argparse or sys?
args = parser.parse_args() parses sys.argv[1:], the list like structure that the command line produced and gave to the Python interpreter. You can also call parse_args with any similar list of strings.
How to split a string like the shell in python?
ipython uses a modified argparse to handle its main input. It uses the config files to populate the parser, giving the user a last minute way of fiddling with the configuration. But its magic commands also parse their arguments with a form of argparse. For that it has its own REPL, rather than using input/raw_input.
Situation:
I am writing a basic templating system in Python/mod_python that reads in a main HTML template and replaces instances of ":value:" throughout the document with additional HTML or db results and then returns it as a view to the user.
I am not trying to replace all instances of 1 substring. Values can vary. There is a finite list of what's acceptable. It is not unlimited. The syntax for the values is [colon]value[colon]. Examples might be ":gallery: , :related: , :comments:". The replacement may be additional static HTML or a call to a function. The functions may vary as well.
Question:
What's the most efficient way to read in the main HTML file and replace the unknown combination of values with their appropriate replacement?
Thanks in advance for any thoughts/solutions,
c
There are dozens of templating options that already exist. Consider genshi, mako, jinja2, django templates, or more.
You'll find that you're reinventing the wheel with little/no benefit.
If you can't use an existing templating system for whatever reason, your problem seems best tackled with regular expressions:
import re
valre = re.compile(r':\w+:')
def dosub(correspvals, correspfuns, lastditch):
def f(value):
v = value.group()[1:-1]
if v in correspvals:
return correspvals[v]
if v in correspfuns:
return correspfuns[v]() # or whatever args you need
# what if a value has neither a corresponding value to
# substitute, NOR a function to call? Whatever...:
return lastditch(v)
return f
replacer = dosub(adict, another, somefun)
thehtml = valre.sub(replacer, thehtml)
Basically you'll need two dictionaries (one mapping values to corresponding values, another mapping values to corresponding functions to be called) and a function to be called as a last-ditch attempt for values that can't be found in either dictionary; the code above shows you how to put these things together (I'm using a closure, a class would of course do just as well) and how to apply them for the required replacement task.
This is probably a job for a templating engine and for Python there are a number of choices. In this stackoveflow question people have listed their favourites and some helpfully explain why: What is your single favorite Python templating engine?