Currently, I have a script which does the following. If I have text file with the lines:
<<Name>> is at <<Location>>.
<<Name>> is feeling <<Emotion>>.
The script will take in the this input file as a command line argument and prompt the user for the variables:
Name? Bob
Location? work
Emotion? frustrated
Note that name is only asked once. The script also takes in an output file as an argument and will place in the file the following.
Bob is at work.
Bob is feeling frustrated.
Now I am trying to extend the script so that I can input the variables from the command line (as if I already knew what it was going to ask). So the command would be like (in this case):
python script.py infile outfile Bob work frustrated
And it would generate the same output. Ideally, the extension should prompt the user for remaining variables if there are more remaining after those put in the command line. So if I run the script as:
python script.py infile outfile Bob work
The script would still prompt:
Emotion?
Excess variables in the command line would be ignored. I am pretty new to Python, so while this seems pretty simple, I haven't had success updating my current script with this add-on. Attached is the script:
import argparse
from os import path
import re
replacements = {}
pattern = '<<([^>]*)>>'
def user_replace(match):
## Pull from replacements dict or prompt
placeholder = match.group(1)
if placeholder in replacements:
return replacements[placeholder]
## .setdefault(key, value) returns the value if present, else sets it then returns
return replacements.setdefault(placeholder, raw_input('%s? ' % placeholder))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('infile', type=argparse.FileType('r'))
parser.add_argument('outfile', type=argparse.FileType('w'))
args = parser.parse_args()
matcher = re.compile(pattern)
for line in args.infile:
new_line = matcher.sub(user_replace, line)
args.outfile.write(new_line)
args.infile.close()
args.outfile.close()
if __name__ == '__main__':
main()
Edit: The input file example above is arbitrary. In actuality, the input file could have any number of variables, repeated any number of times.