Xristos Xristoou wrote: > hello > > > i have one .txt file and i want to create python script with sys.argv or > argparse or other package to define some variables in the txt file and i > take some result. > > > > txt file maybe like this : > > input number 1= %var1% > input number 2= %var2% > result = %vresult(var1-var2)% > > how can i write a python script to update dynamic variables in the txt > file ? i dont want with replace i thing so arguments is the better.
$ cat xristos.txt input number 1= %var1% input number 2= %var2% result = %vresult(var1-var2)% $ cat xristos2.py import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("infile") parser.add_argument("vars", nargs="*") parser.add_argument("--outfile", type=argparse.FileType("w")) args = parser.parse_args() ns = {} exec("\n".join(args.vars), ns) with open(args.infile) as f: text = f.read() parts = text.split("%") for i in range(1, len(parts), 2): parts[i] = str(eval(parts[i], ns)) print("".join(parts), file=args.outfile, end="") $ python3 xristos2.py xristos.txt var1=42 var2=33 'def vresult(a): return a*a' --outfile - input number 1= 42 input number 2= 33 result = 81 Be warned that the text file is now basically a Python script and can do everything a script can do -- including wiping your hard drive. -- https://mail.python.org/mailman/listinfo/python-list