替换基于不同用户输入的字符串(模板配置)-Python



我现在已经使用Python 3天了,所以请原谅noob。

我正在编写一个程序,该程序将在配置模板中使用变量,并有效地进行查找和替换。唯一的区别是,我希望它对用户来说是图形化的(稍后会出现(,并且我希望它是动态的,这样变量就可以在模板之间变化,即模板将以开头

@hostname
@username
@password

下面的配置将在需要的地方包含@hostname等。

hostname @hostname
login @username privilege 15 @password enc sha256

我的find和replace工作得很好,但是当程序在每个@变量之间循环时,它每次都会复制我的模板。所以在这种情况下,我最终会在一个txt文件中堆叠3个模板。

## OPEN TEMPLATE
with open("TestTemplate.txt", "rt") as fin:
with open("out.txt", "w") as fout:
## PULLING VARIABLE NAMES
for line in fin:
if line.startswith("@"):
trimmedLine = line.rstrip()
## USER ENTRY ie Please Enter @username: 
entry = input("Please Enter " + trimmedLine + ": ")
## Open file again to start line loop from the top without affecting the above loop
with open("TestTemplate.txt", "r+") as checkfin:
for line in checkfin:
if trimmedLine in line:
fout.write(line.replace(trimmedLine, entry))
else:
## ENSURE ALL LINES UNAFFECTED ARE WRITTEN
fout.write(line)

正如您所看到的,当它写入所有行时,无论是否未受影响,它都会为循环中的每个迭代执行此操作。我需要它只覆盖受影响的行,同时保留所有其他未受影响的线。我能让它们输出的唯一方法是用fout.write(line)输出每一行,但这意味着我得到的是输出的3倍。

我希望这是清楚的。

谢谢

IDLE的一个例子:
>>> fmtstr = "hostname {} login {} privilege 15 {} enc sha256"
>>> print (fmtstr.format("legitHost", "notahacker", "hunter2"))
hostname legitHost login notahacker privilege 15 hunter2 enc sha256

一旦您拥有了所需的所有数据(主机、用户、密码(,就可以对字符串使用.format( )操作来替换所述字符串中的{}。如果字符串中有多个大括号对,则在如上所示的方法中使用多个逗号分隔的参数,按照它们应该出现的顺序。

我不太清楚你想做什么,所以这可能更适合发表评论,但如果你能解释为什么你没有做以下事情,这将有助于为你提供如何做你想做的事情的建议。

variable_names = #list variables here
variable_values={}
for variable_name in variable_names:
variable_values[variable_name] = input("Please Enter " + variable_name + ": ")
with open("out.txt", "w") as fout:
with open("TestTemplate.txt", "r+") as checkfin:
for line in checkfin:
for variable_name in variable_names:
if variable_name in line:
line = line.replace(variable_name,variable_values[variable_name])
fout.write(line)

最新更新